The Python Oracle

How to get a random number between a float range?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Beneath the City Looping

--

Chapters
00:00 Question
00:22 Accepted answer (Score 935)
00:36 Answer 2 (Score 136)
00:55 Answer 3 (Score 87)
01:22 Answer 4 (Score 15)
01:55 Thank you

--

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

Accepted answer links:
[random.uniform(a, b)]: http://docs.python.org/library/random.ht...

Answer 3 links:
[here]: http://docs.python.org/library/random.ht...

--

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.