In python, what is the difference between random.uniform() and random.random()? In python, what is the difference between random.uniform() and random.random()? python python

In python, what is the difference between random.uniform() and random.random()?


random.random() gives you a random floating point number in the range [0.0, 1.0) (so including 0.0, but not including 1.0 which is also known as a semi-open range). random.uniform(a, b) gives you a random floating point number in the range [a, b], (where rounding may end up giving you b).

The implementation of random.uniform() uses random.random() directly:

def uniform(self, a, b):    "Get a random number in the range [a, b) or [a, b] depending on rounding."    return a + (b-a) * self.random()

random.uniform(0, 1) is basically the same thing as random.random() (as 1.0 times float value closest to 1.0 still will give you float value closest to 1.0 there is no possibility of a rounding error there).


In random.random() the output lies between 0 & 1 , and it takes no input parameters

Whereas random.uniform() takes parameters , wherein you can submit the range of the random number.e.g.
import random as ra print ra.random() print ra.uniform(5,10)

OUTPUT:-
0.672485369423 7.9237539416


Apart from what is being mentioned above, .uniform() can also be used for generating multiple random numbers that too with the desired shape which is not possible with .random()

np.random.seed(99)np.random.random()#generates 0.6722785586307918

while the following code

np.random.seed(99)np.random.uniform(0.0, 1.0, size = (5,2))#generates this array([[0.67227856, 0.4880784 ],       [0.82549517, 0.03144639],       [0.80804996, 0.56561742],       [0.2976225 , 0.04669572],       [0.9906274 , 0.00682573]])

This can't be done with random(...), and if you're generating the random(...) numbers for ML related things, most of the time, you'll end up using .uniform(...)