Generate a random float in Python
This post will discuss how to generate a random float between interval [0.0, 1.0) in Python.
1. Using random.uniform() function
You can use the random.uniform(a, b) function to generate a pseudorandom floating-point number n such that a <= n <= b for a <= b. To illustrate, the following generates a random float in the closed interval [0, 1]:
|
1 2 3 4 5 6 7 |
import random if __name__ == '__main__': rand = random.uniform(0, 1) print(rand) # sample output: 0.8451879617198667 |
2. Using random.random() function
If you need to generate a random floating-point number in the half-open interval [0.0, 1.0), you can call the random.random() function.
|
1 2 3 4 5 6 7 |
import random if __name__ == '__main__': rand = random.random() print(rand) # sample output: 0.7559396034822106 |
3. Using random.randint() function
With the random.randrange() function, you can generate a random floating-point number in the half-open interval [0.0, 1.0) in the following manner:
|
1 2 3 4 5 6 7 |
import random if __name__ == '__main__': rand = random.randrange(1000000) / 1000000 print(rand) # sample output: 0.441964 |
4. Using numpy.random.random() function
If you prefer NumPy, you can use the numpy.random.random() function to generate random floats in the half-open interval [0.0, 1.0).
|
1 2 3 4 5 6 7 |
import numpy as np if __name__ == '__main__': rand = np.random.random() print(rand) # sample output: [0.07855596] |
5. Using numpy.random.random_sample() function
Another solution to generate random floats in the half-open interval [0.0, 1.0) with NumPy is using the numpy.random.random_sample() function.
|
1 2 3 4 5 6 7 |
import numpy as np if __name__ == '__main__': rand = np.random.random_sample() print(rand) # sample output: 0.5320258785026352 |
That’s all about generating a random float in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)