我需要用于模拟的小型高斯随机数列表,所以我尝试了以下方法:
import System.Random
seed = 10101
gen = mkStdGen seed
boxMuller mu sigma (r1,r2) = mu + sigma * sqrt (-2 * log r1) * cos (2 * pi * r2)
Run Code Online (Sandbox Code Playgroud)
这只是Box-Muller算法 - 给定r1,r2在[0,1]区间内的均匀随机数,它返回一个高斯随机数.
normals 0 g = []
normals n g = take n $ map (boxMuller 0 1) $ pairs $ randoms g
where pairs (x:y:zs) = (x,y):(pairs zs)
Run Code Online (Sandbox Code Playgroud)
所以我normals每次需要我的随机数列表时都会使用这个函数.
问题必须明显:它始终生成相同的序列,因为我总是使用相同的种子!我没有得到新的序列,我只是一直得到序列的前n个值.
我明确假装的是,当我输入时:
x = normal 10
y = normal 50
Run Code Online (Sandbox Code Playgroud)
我要将x作为前10个值,将map (boxMuller 0 1) $ …
random haskell functional-programming referential-transparency