简体   繁体   English

在Python Monte Carlo方法中使用Gamma函数估算pi

[英]Estimate pi with Gamma function in Python Monte Carlo method

I'm trying to write a code in python using the Monte Carlo method to estimate pi (where pi = gamma(1/2)**2). 我正在尝试使用蒙特卡洛方法在python中编写代码来估计pi(其中pi = gamma(1/2)** 2)。 I should write a code saying that sqrt(pi) is the area of a square enclosing the function gamma(x=1/2) times the total number of random points generated that end up inside the function, divided by the total number of points generated. 我应该写一个代码,说sqrt(pi)是包围函数gamma(x = 1/2)的正方形的面积乘以函数内部最终生成的随机点的总数,再除以点的总数产生。

Just to show what kind of code I'm talking about, here I did it without using the Gamma function (still is Monte Carlo method). 只是为了显示我正在谈论的代码类型,在这里我没有使用Gamma函数(仍然是Monte Carlo方法)做到了。 Here Pi is evaluated as being the area of a 2x2 square times the number of points ending up in the circle of unit 1 divided by the total number of points generated. 在此,Pi被评估为面积的2x2平方乘以在单元1的圆中结束的点数除以生成的点总数。 The criterion for a point to be in the unit circle is Pythagorean (np.sqrt(x x+y y)<=1). 点在单位圆中的标准是勾股定点(np.sqrt(x x + y y)<= 1)。

inside =0
n=100000
for i in range(0,n):
    x=np.random.rand()
    y=np.random.rand()
    if np.sqrt(x*x+y*y)<=1:
        inside = inside+1
pi = 4.0*inside/n
print pi

I'm not sure how you would determine the area enclosing Gamma(1/2) and what the criterion for a point to end up inside the function would be here. 我不确定如何确定包围Gamma(1/2)的区域以及在函数内结束一点的标准。

Anyone have an idea? 有人有主意吗?

Thanks! 谢谢!

Judging from you question I feel like your are taking PHY324. 从您的问题来看,我觉得您正在服用PHY324。 ;) I am confused about the same thing. ;)我对同一件事感到困惑。 I have a code set up and I am no python expert but maybe this might help. 我设置了代码,但我不是python专家,但这也许会有所帮助。

import random
from math import *

number_of_points = 10000
points_in = []
points_outside = []

for i in range(number_of_points):
    rand_number1 = random.random()
    rand_number2 = random.random()
    if rand_number2 < (exp(-1*rand_number1))*(rand_number1**(-0.5)):
        points_in.append(1)
    else:
        points_outside.append(1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM