用蒙特卡罗方法估计pi会得到比预期更大的值

2024-06-07 11:58:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过划分正方形和它的嵌入圆的面积来估计π,但是我得到了~3.66。你知道吗

有人知道我做错了什么吗?你知道吗

inCount=0
outCount=0
it=1000000
L=100
for i in range(it):
    xran=rnd.random()*L
    yran=rnd.random()*L
    xc=abs(0.5*L-xran)
    yc=abs(0.5*L-yran)
    r=np.sqrt((xc**2)+(yc**2))
    if r<0.5*L:
        inCount=inCount+1
    if r>0.5*L:
        outCount=outCount+1
    if r==0.5*L:
        inCount=inCount+1
        outCount=outCount+1
pigen=inCount/outCount
print('pi generated: '+np.str(pigen))

Tags: ifnpitrandomabs面积xc正方形
3条回答

你有

pigen=inCount/outCount

它给出了半径内外的命中率。你知道吗

请注意,pi/(4-pi) = 3.659792...这是您的代码当前估计的值。你知道吗

你需要

pigen=4*inCount/(inCount+outCount)

这会给你四倍的点击率,即pi。你知道吗


另外请注意,您的代码当前

if r<0.5*L:
    inCount=inCount+1
if r>0.5*L:
    outCount=outCount+1
if r==0.5*L:
    inCount=inCount+1
    outCount=outCount+1

可以用^{}/^{}来简化。因为r不能同时大于和小于L,第二个if可以变成elif。同样,如果r既不小于,也不大于L,那么它必须相等,这样第三个if就可以简单地变成else。你知道吗

if r<0.5*L:
    inCount=inCount+1
elif r>0.5*L:
    outCount=outCount+1
else:
    inCount=inCount+1
    outCount=outCount+1

这将防止在代码中对rL进行不必要的比较。你知道吗


最后的代码是

inCount=0
outCount=0
it=1000000
L=100
for i in range(it):
    xran=rnd.random()*L
    yran=rnd.random()*L
    xc=abs(0.5*L-xran)
    yc=abs(0.5*L-yran)
    r=np.sqrt((xc**2)+(yc**2))
    if r<0.5*L:
        inCount=inCount+1
    elif r>0.5*L:
        outCount=outCount+1
    else:
        inCount=inCount+1
        outCount=outCount+1
pigen=pigen=4*inCount/(inCount+outCount)
print('pi generated: '+np.str(pigen))
inCount+outCount = 4*r^2
inCount = pi*r^2

所以如果你需要pi

pigen=inCount/(outCount+inCount)*4

李维哈几乎是对的!我还忘了加4。你知道吗

如果有人想知道事情进展如何,那就是这样(是的,我可以做你想做的任何事):

import numpy as np
import random as rnd
inCount=0
outCount=0
it=1000000
L=100
for i in range(it):
    xran=rnd.random()*L
    yran=rnd.random()*L
    xc=abs(0.5*L-xran)
    yc=abs(0.5*L-yran)
    r=np.sqrt((xc**2)+(yc**2))
    if r<0.5*L:
        inCount=inCount+1
    if r>0.5*L:
        outCount=outCount+1
    if r==0.5*L:
        inCount=inCount+1
        outCount=outCount+1
pigen=4*inCount/(inCount+outCount)
print('pi generat: '+np.str(pigen))

相关问题 更多 >

    热门问题