You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Scipy quad积分时的最大细分次数超限警告?

解决scipy.integrate.quad的IntegrationWarning问题

问题原因

这个警告是因为quad默认的最大区间细分次数(50次)不足以让积分收敛,你的积分函数在无穷区间上的收敛速度较慢,导致积分器需要更多细分才能达到精度要求。

具体修复方案

1. 化简积分表达式,消除冗余项

原积分式中的(-1/r)*(r²)可直接化简为-r,去掉可能引发数值精度问题的1/r项,简化后的积分式为:

potC = sc.integrate.quad(lambda r: -r * Psi(r,n2) * Psi(r,n1), 0, np.inf)

2. 增加积分器的最大细分次数

通过quad的limit参数调高最大细分次数,给积分器更多收敛的机会:

potC = sc.integrate.quad(lambda r: -r * Psi(r,n2) * Psi(r,n1), 0, np.inf, limit=100)

3. 拆分积分区间

将无穷区间拆分为有限区间和尾部区间(比如[0, 200]和[200, np.inf)),分别积分后求和,每个子区间的积分更容易收敛:

def p(n1,n2):
    part1, _ = sc.integrate.quad(lambda r: -r * Psi(r,n2) * Psi(r,n1), 0, 200)
    part2, _ = sc.integrate.quad(lambda r: -r * Psi(r,n2) * Psi(r,n1), 200, np.inf)
    pot = part1 + part2
    return pot

4. 优化Psi函数的实现

Psi函数可化简为更简洁的形式,减少计算中的数值误差:

def Psi(r,n):
    coeff = 2 / (n ** (3/2))
    return coeff * np.exp(-r/n) * sc.special.hyp1f1(1-n, 2, 2*r/n)

完整修改后的代码示例

import scipy as sc
import numpy as np

def Psi(r,n):
    coeff = 2 / (n ** (3/2))
    return coeff * np.exp(-r/n) * sc.special.hyp1f1(1-n, 2, 2*r/n)

def p(n1,n2):
    potC = sc.integrate.quad(lambda r: -r * Psi(r,n2) * Psi(r,n1), 0, np.inf, limit=100)
    pot = potC[0]
    return pot

print(p(15,15))

内容的提问来源于stack exchange,提问作者Mam Mam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 16:15:43