scipy.integrate.quad关于极限数组

2024-10-03 15:32:15 发布

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

四舍五入整合需要参数func,a,b。其中func是要积分的函数,a和b分别是积分的下限和上限。a和b必须是数字。在

我有一个情况,我需要计算一个函数的积分,对成千上万个不同的a,b求和,并求和结果。这需要很长时间才能循环。我试着给出a和b的四元数组,希望quad能返回相应的数组,但是没有成功。在

这里有一段代码说明了我正在尝试做什么,Python循环可以工作,但速度非常慢,而我尝试的矢量化却不起作用。关于如何快速解决这个问题有什么建议吗?在

import numpy as np
from scipy.integrate import quad

# The function I need to integrate:
def f(x):
    return np.exp(-x*x)

# The large lists of different limits:
a_list = np.linspace(1, 100, 1e5)
b_list = np.linspace(2, 200, 1e5)

# Slow loop:
total_slow = 0  # Sum of all the integrals.
for a, b in zip(a_list, b_list):
    total_slow += quad(f, a, b)[0]
        # (quad returns a tuple where the first index is the result,
        # therefore the [0])

# Vectorized approach (which doesn't work):
total_fast = np.sum(quad(f, a_list, b_list)[0])

"""This error is returned:

 line 329, in _quad
    if (b != Inf and a != -Inf):
ValueError: The truth value of an array with more than 
one element is ambiguous. Use a.any() or a.all()
"""

编辑:

我需要集成的实际函数(rho)还包含两个其他因素。rho0是一个长度与a_list和{}相同的数组。H是标量。在

^{pr2}$

编辑2:

不同解决方案的分析。“space_sylinder”是积分发生的函数。Warren Weckesser的建议与通过一个简单的分析函数传递数组一样快,比慢Python循环快大约500倍(注意程序甚至没有完成的调用次数,它仍然使用657秒)。在

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
# Analytic (but wrong) approximation to the solution of the integral:
      108    1.850    0.017    2.583    0.024 DensityMap.py:473(space_sylinder)
# Slow python loop using scipy.integrate.quad:
       69   19.223    0.279  657.647    9.531 DensityMap.py:474(space_sylinder)
# Vectorized scipy.special.erf (Warren Weckesser's suggestion):
      108    1.786    0.017    2.517    0.023 DensityMap.py:475(space_sylinder)

Tags: ofthe函数isnpspacescipy数组
1条回答
网友
1楼 · 发布于 2024-10-03 15:32:15

exp(-x*x)的积分是error function的缩放版本,因此可以使用^{}来计算积分。给定标量ab,函数从a到{}的积分是0.5*np.sqrt(np.pi)*(erf(b) - erf(a))。在

erf"ufunc",这意味着它处理数组参数。给定a_listb_list,您的计算可以写成

total = 0.5*np.sqrt(np.pi)*(erf(b_list) - erf(a_list)).sum()

函数rho也可以使用erf处理,方法是使用适当的缩放:

^{pr2}$

在依赖它之前,对照你的慢解决方案检查一下。对于某些值,erf函数的减法会导致显著的精度损失。在

相关问题 更多 >