Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a random float with step in Python

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.

like image 204
SkyWalker Avatar asked Aug 14 '12 09:08

SkyWalker


People also ask

How do you use float randomly?

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 .

How do you get a random float between 0 and 1 in Python?

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.

What is step in Randrange in Python?

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.


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
like image 91
eumiro Avatar answered Sep 24 '22 11:09

eumiro


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
like image 29
Paulo Scardine Avatar answered Sep 24 '22 11:09

Paulo Scardine