改进蒙特卡罗程序求高维球体体积。(Python)

2024-04-23 18:18:18 发布

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

考虑高斯形状,我们可以求出一个球体的n维体积。我的目的是用蒙特卡罗方法求体积。在

利用高斯积分,我找到了公式

enter image description here

我的理解是,n维球体内部的点与总点数的比率,将大致等于球体积与立方体体积的比率。我的意思是质量密度永远不会改变,不管我用什么尺寸。在

因此,我假设我应该遵循我用蒙特卡罗方法求π值的相同方法。在

我不明白如何遵循我评估的代码来找到pi的值。在

import random

TIMES_TO_REPEAT = 10**5
LENGTH = 10**5

def in_circle(x, y):
    return x**2 + y**2 < LENGTH**2

inside_count = 0
for _ in range(TIMES_TO_REPEAT):
    point = random.randint(0,LENGTH), random.randint(0,LENGTH)
    if in_circle(*point):
        inside_count += 1

pi = (inside_count / TIMES_TO_REPEAT) * 4

print(pi) 

我如何在我提到的代码中应用不等式条件,使质量密度相同,并且我可以在更高的维度上找到体积的值。?在


Tags: to方法incountpi质量体积random
2条回答

基本思想是:如果一个圆(半径为$R$)内接在一个正方形内(那么它的边必须是$2R$),那么这个比率(圆的面积与正方形的面积之比)将是$\pi/4$。所以,如果你在方格内随机选取$N$个点,大约$N*\pi/4$应该落在圆圈内。在

希望注释/修改后的代码能帮助您理解MC逻辑

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
import random

N = 10**5 # number of trials (ie, number of points to sample)
R = 10**5 # circle radius

def in_sphere(x, y, z):
    return x**2 + y**2 + z**2 < R**2

c = 0
for _ in range(N):
    p = random.randint(0,R), random.randint(0,R), random.randint(0,R)
    if in_sphere(*p):
        c += 1

pi = 6 * c / N
print(pi)

相关问题 更多 >