Python random.random() Method



The Python random.random() method returns a random float r, such that 0 is less than or equal to r and r is less than 1.

The return values are picked at pseudo-randomly from that range with a uniform distribution. This method creates a single new pseudorandom number generator when it is first called.

After that, this new pseudorandom number generator is used for all calls to this method and is nowhere else used. This method is correctly synchronized to permit proper use by multiple threads. However, it may reduce contention for each thread to have its own pseudorandom-number generator if several threads need to generate pseudorandom numbers at a high rate.

Syntax

Following is the syntax of Python random.random() method −

math.random()

Note − This function is not accessible directly, so we need to import random module and then we need to call this function using random static object.

Parameters

This method does not accept any parameter.

Return Value

This method returns a random float r, such that 0 is less than or equal to r and r is less than 1.

Example

The following example shows the usage of the Python random.random() method.

import random
# First random number
print ("random() : ", random.random())
# Second random number
print ("random() : ", random.random())

When we run above program, it produces following result −

random() :  0.281954791393
random() :  0.309090465205

Example

In the following example an integer object 'num' is created with the value '28'. Then a random number is generated between the given range which is 1 and 28 using random() method. The result is then returned:

import random
num = 28
res = random.random()*num
print ("The random number generated is: ",res)

We get different random numbers each time we execute the above code between the given range as shown below:

The random number generated is:  12.07474794643971
The random number generated is:  8.78791775636994
The random number generated is:  0.021456529855730544

Example

In the example given below an integer object 'num' is created with the value '45'. Then we set the initial value as 254 and the final value as 45 for generating random numbers using random() method. Therefore, the random numbers will be between 254 and (254 + (45-1)) i.e. 254 and 298:

import random
num = 45
res = 254 + (random.random()*num)
print ("The random number generated is: ",res)

Following is an output of the above code −

The random number generated is:  260.5154180979666
The random number generated is:  278.33487159953995
python_numbers.htm
Advertisements