如何在scipy.optimize.fsolve触发RuntimeWarning时终止程序
解决方案
方法1:将指定RuntimeWarning转为异常,触发程序自动终止
你可以通过Python的warnings模块,将匹配到的maxfev超限警告转为异常,程序遇到异常就会自动终止运行:
import warnings from scipy.optimize import fsolve # 配置警告过滤规则:将匹配到的maxfev超限RuntimeWarning转为错误抛出 warnings.filterwarnings('error', category=RuntimeWarning, message=r'The number of calls to function has reached maxfev = \d+\.') # 你的求解代码 try: sol = fsolve(f, [1e-6,1e-6], xtol=1e-6, maxfev=20, full_output=False, col_deriv=True) except RuntimeWarning as e: print(f"求解失败,告警信息:{e}") # 终止程序,退出码可自定义 exit(1)
方法2:通过返回结果判断收敛状态(更可控,推荐)
开启full_output=True参数获取求解的完整状态信息,通过返回的收敛标志位判断是否求解成功,失败时主动终止程序:
from scipy.optimize import fsolve # 开启full_output获取完整输出 sol, infodict, ier, mesg = fsolve(f, [1e-6,1e-6], xtol=1e-6, maxfev=20, full_output=True, col_deriv=True) # ier=1代表求解收敛成功,其他值均为失败 if ier != 1: print(f"求解失败,告警信息:{mesg}") exit(1)
返回参数ier的常见取值含义:
- 1:求解收敛成功
- 2:已达到最大函数调用次数maxfev
- 3:算法遇到了无穷大或者NaN的结果
- 4:求解过程中出现了奇异矩阵
- 5:算法无法收敛到容差要求的精度
内容的提问来源于stack exchange,提问作者spc_CH
相关产品推荐
相关产品推荐

