擅长:python、mysql、java
<p>基本思想是:如果一个圆(半径为$R$)内接在一个正方形内(那么它的边必须是$2R$),那么这个比率(圆的面积与正方形的面积之比)将是$\pi/4$。所以,如果你在方格内随机选取$N$个点,大约$N*\pi/4$应该落在圆圈内。在</p>
<p>希望注释/修改后的代码能帮助您理解MC逻辑</p>
<pre><code>import random
N = 10**5 # number of trials (ie, number of points to sample)
R = 10**5 # circle radius
# whether p(x,y) is inside a circle
def in_circle(x, y):
return x**2 + y**2 < R**2
# use integer ops as much as possible for speed
c = 0
for i in range(N):
x, y = random.randint(0,R), random.randint(0,R)
if in_circle(x, y):
c += 1
pi = 4 * c / N
print(pi) # pi-> 3.14
</code></pre>