我正在尝试使用park-miller算法生成随机数。我知道一般的想法应该是:
seed = (16807*seed) % (2147483947)
但我不确定如何实际将其实现为python。我如何指定从0-9返回一个数字?
答案 0 :(得分:0)
使用生成器,然后由于该模运算,您知道该值在0-2147483947中,然后使用简单的线方程y=a*x+b
将值映射到新范围
def park_miller(seed,start,end):
a = (end-start)/2147483947
b = start
while True:
seed = (16807*seed) % 2147483947
yield a * seed +b
这里有一些测试
>>> rand=park_miller(8,0,1)
>>> next(rand)
6.261094532875687e-05
>>> next(rand)
0.05230215814041659
>>> next(rand)
0.04237186598163661
>>> next(rand)
0.14395155336637308
>>> next(rand)
0.39375742863236407
>>>
>>> rand=park_miller(8,0,10)
>>> next(rand)
0.0006261094532875686
>>> next(rand)
0.5230215814041659
>>> next(rand)
0.42371865981636603
>>> next(rand)
1.4395155336637309
>>> next(rand)
3.9375742863236405
>>> next(rand)
8.811030241428854
>>> next(rand)
6.985267694762423
>>> next(rand)
1.394145872048281
>>>
>>> rand=park_miller(42,0,10)
>>> [next(rand) for _ in range(20)]
[0.0032870746297597353, 5.245863302371871, 7.224522964035922,
2.5574565517345866, 3.1722650031991133, 6.257908767501488,
6.672655397502722, 7.319265828253476, 4.9007754561808605,
7.333092031723578, 7.277777178187214, 7.601033792500801,
0.5749505609691992, 3.1940782093306144, 2.8724642196359103,
7.506139420747902, 5.685244510002383, 1.9044796100634134,
8.588806335789574, 2.0680856153566394]
>>>