Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In python for the random module, what is the difference between random.uniform() and random.random()? They both generate pseudo random numbers, random.uniform() generates numbers from a uniform distribution and random.random() generates the next random number. What is the difference?

like image 394
NKCP Avatar asked May 04 '15 12:05

NKCP


People also ask

What is random uniform ()?

Python Random uniform() Method The uniform() method returns a random floating number between the two specified numbers (both included).

What does random () do in python?

The random() method returns a random floating number between 0 and 1.

What is the difference between NP random rand () and NP random Randn ()?

randn generates samples from the normal distribution, while numpy. random. rand from a uniform distribution (in the range [0,1)).


2 Answers

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).

like image 102
Martijn Pieters Avatar answered Sep 20 '22 20:09

Martijn Pieters


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

like image 29
Storm Avatar answered Sep 20 '22 20:09

Storm