如何在 Python 中获得具有步长的随机浮点数

8

仍在努力弄清楚Python中是否有一个函数可以获得具有步长的随机浮点值?类似于randrange(start, stop, step)但适用于浮点数。

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

使用 int(round(...)) 比使用 int(...) 更安全,特别是当 stop - start 接近于 step 的倍数时。否则很难预测 stop 是否是可能的值。 - Mark Dickinson

1

只需乘以适当的常数即可得到整数,并对结果进行相反的操作。

start = 1.5
stop  = 4.5
step  = 0.3
precision = 0.1
f = 1 / precision
random.randrange(start*f, stop*f, step*f)/f

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接