The Python Oracle

How to get a random number between a float range?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Unforgiving Himalayas Looping

--

Chapters
00:00 How To Get A Random Number Between A Float Range?
00:13 Accepted Answer Score 1011
00:24 Answer 2 Score 148
00:39 Answer 3 Score 89
00:58 Answer 4 Score 16
01:24 Answer 5 Score 16
01:48 Thank you

--

Full question
https://stackoverflow.com/questions/6088...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #random #floatingpoint

#avk47



ACCEPTED ANSWER

Score 1022


Use random.uniform(a, b):

>>> import random
>>> random.uniform(1.5, 1.9)
1.8733202628557872



ANSWER 2

Score 149


if you want generate a random float with N digits to the right of point, you can make this :

round(random.uniform(1,2), N)

the second argument is the number of decimals.




ANSWER 3

Score 89


random.uniform(a, b) appears to be what your looking for. From the docs:

Return a random floating point number N such that a <= N <= b for a <= b and b <= N <= a for b < a.

See here.




ANSWER 4

Score 16


Most commonly, you'd use:

import random
random.uniform(a, b) # range [a, b) or [a, b] depending on floating-point rounding

Python provides other distributions if you need.

If you have numpy imported already, you can used its equivalent:

import numpy as np
np.random.uniform(a, b) # range [a, b)

Again, if you need another distribution, numpy provides the same distributions as python, as well as many additional ones.