How to get random float with step in Python

Still trying to figure out if there is a function in Python to get a random float value in steps? Like randrange (start, stop, step), but for float.

+4
source share
2 answers
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 
+4
source

Just multiply for some suitable constant to get integers and cancel the operation on 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 
+1
source

All Articles