Still trying to figure out if there is a function in Python to get a random float value with step? Similar to randrange(start, stop, step) but for floats.
If you want to generate a random number between a custom range, you can use the following format: minnumber + (random-float (maxnumber - minnumber)) . For example, if we wanted to generate a random floating point number between 4 and 7, we would write the following code: 4 + random-float 3 .
uniform() function. The random. uniform() function is perfectly suited to generate a random number between the numbers 0 and 1, as it is utilized to return a random floating-point number between two given numbers specified as the parameters for the function.
randrange() in Python Python offers a function that can generate random numbers from a specified range and also allowing rooms for steps to be included, called randrange() in random module.
import random
def randrange_float(start, stop, step):
return random.randint(0, int((stop - start) / step)) * step + start
randrange_float(2.1, 4.2, 0.3) # returns 2.4
Just multiply for some appropriate constant in order to get integers and reverse the operation over the result.
start = 1.5
stop = 4.5
step = 0.3
precision = 0.1
f = 1 / precision
random.randrange(start*f, stop*f, step*f)/f
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