简体   繁体   English

改进蒙特卡洛代码以找到高维球体的体积。 (PYTHON)

[英]Improving a Monte Carlo code to find the volume of sphere in Higher dimension. (PYTHON)

Considering Gaussian shape we can find the volume of n dimensional volume of a sphere.考虑到高斯形状,我们可以找到球体的 n 维体积的体积。 My intention is to find the volume using Monte Carlo method.我的意图是使用蒙特卡洛方法找到体积。

Using the gaussian integral I have found the formula使用高斯积分我找到了公式

在此处输入图像描述

What I understand that the ratio of the points inside the n-dimensional sphere to the total number of points will then be roughly the same as the ratio of the volume of the ball to that of the cube.据我了解,n 维球体内的点与点总数的比率将大致与球的体积与立方体的体积之比相同。 I mean the mass density would never change, whatever dimension I use.我的意思是质量密度永远不会改变,无论我使用什么维度。

Therefore I assume I should follow the same technique what I used to find the value of pi using Monte Carlo method.因此,我假设我应该遵循与使用蒙特卡洛方法查找 pi 值时相同的技术。

I don't understand how to follow the code which I evaluated to find the value of pi.我不明白如何按照我评估的代码来找到 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) 

How can I apply the inequality condition in the code I have mentioned so the mass density would be same and I can find the value of volume in Higher dimension.?我如何在我提到的代码中应用不等式条件,以便质量密度相同,并且我可以找到更高维度的体积值。?

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)

The basic idea: if a circle (radius R ) is inscribed inside a square (then, its edge must be 2R ), then the ratio (the area of circle over the area of square) will be π/4 .基本思想:如果一个圆(半径R )内切在一个正方形内(那么,它的边必须是2R ),那么比率(圆的面积与正方形的面积之比)将为π/4 So, if you pick N points at random inside the square, approximately N * π/4 of those points should fall inside the circle.因此,如果您在正方形内随机选择N个点,则这些点中大约有N * π/4应该落在圆内。

hope the annotated/revised code help you understand the MC logic希望注释/修改后的代码能帮助您理解 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

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

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