9

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.

2 Answers 2

10
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
Sign up to request clarification or add additional context in comments.

1 Comment

Using int(round(...)) may be a little safer than using int(...), especially if it'll usually be the case that stop - start is close to a multiple of step. Otherwise it's difficult to predict whether stop will be a possible value or not.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.