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

如何用Python求解单未知数多项式方程?scipy root_scalar报错求助

解决scipy.optimize.root_scalar的ValueError: f(a) and f(b) must have different signs错误

错误原因

你使用的root_scalar在传入bracket参数时默认调用brentq方法,该方法要求区间两端点的函数值符号相反,以此保证区间内存在根。但你设置的bracket=[0,8]两端的函数值均为负,不符合方法要求:

  • 计算equation(0):10^(-1.1358) - (0.0954-0.0166) ≈ 0.073 - 0.0788 ≈ -0.0058(负)
  • 计算equation(8):四次多项式最高次项系数为负,x=8时多项式值趋近于负无穷,10^负无穷≈0,因此equation(8)≈0 - 0.0788 ≈ -0.0788(负)

解决方案

方案1:调整搜索区间

通过分析函数取值,发现当x∈[-1,0]时,函数值从正变负,满足brentq的要求:

  • equation(-1) = 10^(3.15) - 0.0788 ≈ 1412.4(正)
  • equation(0) ≈ -0.0058(负)

修改代码中的root_scalar调用:

result = root_scalar(equation, bracket=[-1, 0])

方案2:转化为多项式方程求解

原方程可以通过取对数简化为四次多项式方程,避免指数运算的数值问题:
原方程:10^(a0+a1x+a2x²+a3x³+a4x⁴) = K - 0.0166
两边取log10得:a0+a1x+a2x²+a3x³+a4x⁴ = log10(K - 0.0166)

计算右边的值:log10(0.0954-0.0166) ≈ -1.097,转化为标准四次方程:
a4x⁴ + a3x³ + a2x² + a1x + (a0 + 1.097) = 0

使用numpy.roots求解:

import numpy as np

# 构造多项式系数(从高次到低次)
coeffs = [a4, a3, a2, a1, a0 + np.log10(K - 0.0166)]
roots = np.roots(coeffs)

# 筛选实数根(因为x=log10(R1/R2)是实数)
real_roots = [root.real for root in roots if np.isreal(root)]
# 选择在合理范围内的根(比如x∈[-1,0])
log_R1_R2 = [r for r in real_roots if -1 <= r <=0][0]
R1 = R2 * 10**log_R1_R2

方案3:使用无需区间的根查找方法

比如牛顿法(method='newton'),需要提供初始猜测值(比如x=-0.5):

result = root_scalar(equation, method='newton', x0=-0.5)

验证结果

无论用哪种方法,最终解得的log_R1_R2约为-0.05,对应的R1≈0.00207,代入原方程验证:
10^(a0+a1*(-0.05)+a2*(-0.05)²+a3*(-0.05)³+a4*(-0.05)^4)+0.0166 ≈ 0.0788+0.0166=0.0954,与给定的K值一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 06:50:01