我尝试用Box-Muller变换和Marsaglia极性方法来测试从正态分布生成数字的速度。据说Marsaglia极坐标法比Box-Muller变换快,因为它不需要计算sin和cos。但是,当我用Python编写代码时,这不是真的。有人能证实这一点或向我解释为什么会这样吗?在
def marsaglia_polar():
while True:
x = (random.random() * 2) - 1
y = (random.random() * 2) - 1
s = x * x + y * y
if s < 1:
t = math.sqrt((-2) * math.log(s)/s)
return x * t, y * t
def box_muller():
u1 = random.random()
u2 = random.random()
t = math.sqrt((-2) * math.log(u1))
v = 2 * math.pi * u2
return t * math.cos(v), t * math.sin(v)
为了“好玩”,我把它写在围棋里。
box_muller
函数在那里也更快。而且,它比python版本快10倍左右。在输出:
^{pr2}$相关问题 更多 >
编程相关推荐