I want to generate a floating point random number with two precision.
For example:2.54
How to change the uniform(a,b)
in python.
Thanks
In Python, to print 2 decimal places we will use str. format() with “{:. 2f}” as string and float as a number. Call print and it will print the float with 2 decimal places.
Use a random. random() function of a random module to generate a random float number uniformly in the semi-open range [0.0, 1.0) . Note: A random() function can only provide float numbers between 0.1. to 1.0. Us uniform() method to generate a random float number between any two numbers.
format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.
You can use round function with uniform function to limit float number to two decimal places.
Example:
round(random.uniform(1.5, 1.9),2)
Out[]: 1.62
round(random.uniform(1.5, 1.9),3)
Out[]: 1.885
If you want to generate a random number between two numbers, with a specific amount of decimals, here is a way:
import random
greaterThan = float(1)
lessThan = float(4)
digits = int(2)
rounded_number = round(random.uniform(greaterThan, lessThan), digits)
in this case, your random number will be between 1 and 4, with two digits
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With