小编Dyl*_*zzo的帖子

区域体积的Python数值积分

对于程序,我需要一种算法来快速计算实体的体积.该形状由一个函数指定,给定点P(x,y,z),如果P是实体的点,则返回1,如果P不是实体的点,则返回0.

我尝试使用numpy使用以下测试:

import numpy
from scipy.integrate import *
def integrand(x,y,z):
    if x**2. + y**2. + z**2. <=1.:
        return 1.
    else:
        return 0.
g=lambda x: -2.
f=lambda x: 2.
q=lambda x,y: -2.
r=lambda x,y: 2.
I=tplquad(integrand,-2.,2.,g,f,q,r)
print I
Run Code Online (Sandbox Code Playgroud)

但它没有给我以下错误:

警告(来自警告模块):文件"C:\ Python27\lib\site-packages\scipy\integrate\quadpack.py",第321行warnings.warn(msg,IntegrationWarning)IntegrationWarning:最大细分数(50)已经实现了.如果增加限制没有产生任何改进,建议分析被积函数以确定困难.如果可以确定局部难度的位置(奇点,不连​​续),则可能从分割区间并在子范围上调用积分器获得.也许应该使用专用集成商.

警告(来自警告模块):文件"C:\ Python27\lib\site-packages\scipy\integrate\quadpack.py",第321行warnings.warn(msg,IntegrationWarning)IntegrationWarning:算法不收敛.在外推表中检测到舍入误差.假设无法实现所请求的容差,并且返回的结果(如果full_output = 1)是可以获得的最佳结果.

警告(来自警告模块):文件"C:\ Python27\lib\site-packages\scipy\integrate\quadpack.py",第321行warnings.warn(msg,IntegrationWarning)IntegrationWarning:检测到舍入错误的发生,其中防止达到要求的容差.错误可能被低估了.

警告(来自警告模块):文件"C:\ Python27\lib\site-packages\scipy\integrate\quadpack.py",第321行warnings.warn(msg,IntegrationWarning)IntegrationWarning:积分可能是发散的,或者是慢慢收敛的.

所以,很自然地,我寻找"专用集成商",但找不到任何可以做我需要的东西.

然后,我尝试使用蒙特卡罗方法编写自己的集成,并使用相同的形状对其进行测试:

import random

# Monte Carlo Method
def get_volume(f,(x0,x1),(y0,y1),(z0,z1),prec=0.001,init_sample=5000):
    xr=(x0,x1)
    yr=(y0,y1)
    zr=(z0,z1)
    vdomain=(x1-x0)*(y1-y0)*(z1-z0)
    def rand((p0,p1)):
        return p0+random.random()*(p1-p0)
    vol=0.
    points=0.
    s=0.  # sum part of variance of f
    err=0.
    percent=0
    while err>prec …
Run Code Online (Sandbox Code Playgroud)

python algorithm numpy montecarlo numerical-methods

7
推荐指数
1
解决办法
3792
查看次数

标签 统计

algorithm ×1

montecarlo ×1

numerical-methods ×1

numpy ×1

python ×1