本文介绍了使用scipy.integrate.quad执行3D积分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在所有空间上集成函数f(x,y,z).

I'm trying to integrate a function f(x,y,z) over all space.

我尝试使用scipy.integrate.tplquad& scipy.integrate.nquad用于积分,但是两种方法都将积分返回为0(当积分应为有限值时).这是因为,随着积分量的增加,对被积分数为非零的区域的采样越来越少.积分缺少"该空间区域.但是,scipy.integrate.quad似乎可以通过执行变量更改来处理[-infinity,infinity]中的积分...

I have tried using scipy.integrate.tplquad & scipy.integrate.nquad for the integration, but both methods return the integral as 0 (when the integral should be finite). This is because, as the volume of integration increases, the region where the integrand is non-zero gets sampled less and less. The integral 'misses' this region of space. However, scipy.integrate.quad does seem to be able to cope with integrals from [-infinity, infinity] by performing a change of variables...

是否可以使用scipy.integrate.quad 3次来执行三重积分.我想到的代码如下所示:

Is it possible to use scipy.integrate.quad 3 times to perform a triple integral. The code I have in mind would look something like the following:

x_integral = quad(f, -np.inf, np.inf)
y_integral = quad(x_integral, -np.inf, np.inf)
z_integral = quad(y_integral, -np.inf, np.inf)

其中,f是函数f(x,y,z),x_integral应该从x = [-无穷大,无穷大]进行积分,y_integral应该从y = [-无穷大,无穷大]进行积分,而z_integral应该从z = [-无限,无限].我知道quad要返回浮点数,因此不喜欢在x上集成函数f(x,y,z)以返回y和z的函数(如上面代码中的x_integral = ...行)正在尝试这样做).有没有办法实现上面的代码?

where f is the function f(x, y, z), x_integral should integrate from x = [- infinity, infinity], y_integral should integrate from y = [- infinity, infinity], and z_integral should integrate from z = [- infinity, infinity]. I am aware that quad wants to return a float, and so does not like integrating a function f(x, y, z) over x to return a function of y and z (as the x_integral = ... line from the code above is attempting to do). Is there a way of implementing the code above?

谢谢

推荐答案

下面是对quad的嵌套调用的示例,该调用执行积分以给出1/8的球体体积:

Here is an example with nested call to quad performing the integration giving 1/8th of the sphere volume:

import numpy as np
from scipy.integrate import quad

def fz(x, y):
    return quad( lambda z:1, 0, np.sqrt(x**2+y**2) )[0]

def fy(x):
    return quad( fz, 0, np.sqrt(1-x**2), args=(x, ) )[0]

def fx():
    return quad( fy, 0, 1 )[0]

fx()
>>> 0.5235987755981053

4/3*np.pi/8
>>> 0.5235987755982988

这篇关于使用scipy.integrate.quad执行3D积分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 15:45