从飞镖扔到球形飞镖板(Python)的飞镖中估算PI
估计PI的熟悉代码如下:
import math,random
random.seed(777)
j = pie = 1
while True:
pie = pie + math.trunc(random.random()**2 + random.random()**2)
if j%100000==0: print(4*(1-float(pie)/float(j)))
j = j + 1
print('done')
模拟飞镖在二维飞镖板上投掷。 但是,当您尝试提升到三维飞镖板时,
import math,random
random.seed(777)
j = pie = 1
while True:
pie = pie + math.trunc(random.random()**2 + random.random()**2 + random.random()**2)
if j%100000==0: print((3.0/4.0)*8.0*(1-float(pie)/float(j)))
j = j + 1
print('done')
您会得到PI以外的其他东西。
The familiar code for estimating pi is as follows:
import math,random
random.seed(777)
j = pie = 1
while True:
pie = pie + math.trunc(random.random()**2 + random.random()**2)
if j%100000==0: print(4*(1-float(pie)/float(j)))
j = j + 1
print('done')
which emulates darts being thrown at a two-dimensional dartboard.
But when you try to elevate to a three-dimensional dartboard with:
import math,random
random.seed(777)
j = pie = 1
while True:
pie = pie + math.trunc(random.random()**2 + random.random()**2 + random.random()**2)
if j%100000==0: print((3.0/4.0)*8.0*(1-float(pie)/float(j)))
j = j + 1
print('done')
you get something other than pi.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通常,我同意@bob__提出的解决方案,因为它更简单。
话虽如此,您的解决方案可以推广到3维dartboard:
要了解问题,我们需要澄清
pie> pie
变量的真正作用。它包含随机半径长于1.0(超出3D飞镖)的情况。2D案例之所以有效,是因为
MATH.TRUNC
始终返回0或1(in或out),但对于3D,它返回0或1或2。将PIE
增加2,从而将收敛速度更快。要解决您的示例,您只需要确保一次
pie
一次不会增加1个即可。Generally, I agree with the solution proposed by @Bob__ as it's more straightforward.
Having said that, your solution can be generalized to 3 dimensional dartboard:
To understand the issue we need to clarify what the
pie
variable really does. It contains the number of cases where a random radius is longer than 1.0 (so beyond the 3D dartboard).The 2D case works because
math.trunc
always returns either 0 or 1 (in or out) but for 3D it returns either 0 or 1 or 2. So, in case of 3D, it fails because it sometimes increasespie
by 2 and, thus, converges faster.To fix your example, you just need to make sure that
pie
is never increased by more than 1 at a time.