python利用Monte Carlo方法计算圆周率

Posted zolty

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python利用Monte Carlo方法计算圆周率相关的知识,希望对你有一定的参考价值。

from random import random


def cal(n):
    count = 0
    for i in range(1, n):
        x = random()
        y = random()
        if x*x + y*y <= 1:
            count += 1
    print("pi:", 4*count/n)


if __name__ == '__main__':
    cal(10000000)

from random import random, uniform


# cal pi
def p(n):
    print(random())
    count = 0
    for i in range(1, n):
        x = random()
        y = random()
        if x*x + y*y <= 1:
            count += 1
    print("pi:", 4*count/n)


# x^2 [0, 1]
def x2(n):
    count = 0
    for i in range(1, n):
        x = random()
        y = random()
        if y < x*x:
            count += 1
    print("res:", count/n)


# x^2 [2,5]
def x22(n):
    count = 0
    for i in range(1, n):
        x = uniform(2, 5)
        y = uniform(0, 25)
        if y < x*x:
            count += 1
    print("res", 75 * count/n)


# x^2 [2,5]
def c(n):
    a = 2
    b = 5
    x = uniform(a, b)
    s = 0
    for i in range(1, n):
        s += (x*x) / (3/117 * x * x)
    print("res", s/n)


if __name__ == '__main__':
    p(10000000)
    x2(10000000)
    x22(10000000)
    c(10000000)

参考文献

蒙特卡洛(Monte Carlo, MCMC)方法的原理和应用[https://www.bilibili.com/video/BV17D4y1o7J2?p=3&spm_id_from=pageDriver]

以上是关于python利用Monte Carlo方法计算圆周率的主要内容,如果未能解决你的问题,请参考以下文章

python利用Monte Carlo方法计算圆周率

蒙特卡洛(Monte Carlo)方法计算π

蒙特卡洛(Monte Carlo)方法计算π

蒙特卡罗(Monte Carlo) 模拟

蒙特卡罗方法(Monte Carlo method)

蒙特卡洛(Monte Carlo)方法求面积