randrange(start, stop) only takes integer arguments. So how would I get a random number between two float values?
Asked
Active
Viewed 6e+01k times
591
martineau
- 112,593
- 23
- 157
- 280
Mantis Toboggan
- 6,505
- 3
- 18
- 10
-
8If you wanted numpy it's `np.random.uniform(start, stop)` or `np.random.uniform(start, stop, samples)` if you wanted multiple samples. Otherwise below answers are best. – sachinruk Dec 04 '19 at 00:33
5 Answers
882
Use random.uniform(a, b):
>>> random.uniform(1.5, 1.9)
1.8733202628557872
Yuri Stuken
- 11,890
- 1
- 25
- 23
-
8could this theoretically produce 1.5 and 1.9? or would it only ever produce 1.50~1 and 1.89~? – Musixauce3000 Apr 29 '16 at 13:39
-
28@Musixauce3000 Short Answer: Yes. Longer answer: If you look at the documentation it states `Returns a random floating point number N such that a <= N <= b for a <= b and b <= N <= a for b < a` In other words the output `N` can equal either input `a` and `b`. In this case `1.5` and `1.9`. – Dan Mar 01 '17 at 13:37
-
Is there another way to do this without using the `.uniform` function, but instead with either `.random` or `randrange`? – EnigmaTech Mar 27 '19 at 10:12
-
1@DerryckDX `1.5 + random.random() * (1.9 - 1.5)` should do it, even though according to the specs this will never return exactly `1.9` (even in theory). – Yonatan N Mar 29 '19 at 00:03
-
2@Musixauce3000 it seems `uniform(a, b)` is implemented as `a + (b-a) * random()` and returns *a random number in the range [a, b) or [a, b] depending on rounding* https://github.com/python/cpython/blob/963eb0f4738456455b9bef7eb531b46805415208/Lib/random.py#L415 – Pavel Jun 04 '19 at 08:47
124
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.
Baurin Leza
- 1,796
- 1
- 12
- 14
14
From my experience dealing with python, I can only say that the random function can help in generating random float numbers. Take the example below;
import random
# Random float number between range 15.5 to 80.5
print(random.uniform(15.5, 80.5))
# between 10 and 100
print(random.uniform(10, 100))
The random.uniform() function returns a random floating-point number between a given range in Python
The two sets of code generates random float numbers. You can try experimenting with it to give you what you want.
DrosnickX
- 387
- 4
- 9
11
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.
stwykd
- 2,365
- 2
- 15
- 19