How to generate random floating numbers in Python
In this tutorial, we will learn how to get float numbers between two numbers using Python. To get a random floating number we will use random.uniform() function this will give a float number between a given range. We can also round these floating numbers using the round() function in Python. This link will help to understand How to Round Numbers in Python Language.
We can get float numbers between closed 0 to open 1 using random.random() function. We can also get a random number between any range using the same function. You can look into implementation in the below codes.
Let’s look into a few implementations:
random.uniform() method example:
#importing required libraries import random #getting random float number between two float numbers using uniform method ran_flo=random.uniform(6.66,15.99) print(ran_flo)
Output:
11.77998206000711
Code to round off the random float
If you want to stick to a fixed number of decimals then you can round it off to a required number of decimals. Here is the implementation for this.
#importing required libraries import random #getting random float number between two float numbers using uniform method ran_flo=random.uniform(6.66,15.99) ran_flo=round(ran_flo,3) print(ran_flo)
Output:
8.476
Code using random.random() function
the random library also provides a function to get float number using random function. This function gives a random number between 0 to 1.00. [0,1.0).
Here is the implementation for this function:
#importing required libraries import random #getting random float number between 0 to 1 ran_flo=random.random() print(ran_flo)
Output:
0.625927267696903
You can also round this using the above example.
Getting random float between any range of numbers
We can also get random float number between any range using random.random() function. Here is the implementation for this.
#importing required libraries import random st=10 la=40 #getting random float number between st to la ran_flo=st+(random.random())*(la-st) print(ran_flo)
Output:
36.406551704457094
Leave a Reply