我试图在求解方程组后找到直线的交点,结果显示“ValueError:fun
最多只能返回一维array_like. f0.形状:(2,100)'。不太确定我哪里错了。
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import least_squares
import scipy.interpolate, scipy.optimize
k1 = 10**(-9.25)
k2 = 10**(-18.26)
k3 = 10**(-35.91)
logk = 11.96
pH_x = np.linspace(0, 14, 100)
ni_total = 0.1
n_total = 1.2
T_ = 298
h = 10**(-pH_x)
def equations(p):
nh4, nio2 = p
f = 10**(logk - 2 * pH_x)
ni2pfree = f/(1 + f / ni_total)
nh3 = k1 * nh4 / h
nin4p2 = k2 * (nh4**4) / (h**2)
nin6p2 = k3 * (nh4**6) / (h**4)
return (n_total-nh3-4*nin4p2-6*nin6p2-nh4,
ni_total - ni2pfree - nin4p2- nin6p2- nio2)
res = least_squares(equations, (0.1, 0.1), bounds=((0, 0), (n_total,ni_total )),method='dogbox',xtol=1e-12)
nh4 =res.x[0]
nio2 =res.x[1]
f = 10**(logk - 2 * pH_x)
ni2pfree = f / (1 + f / ni_total)
nh3 = k1 * nh4 / h
nin4p2 = k2 * (nh4**4) / (h**2)
nin6p2 = k3 * (nh4**6) / (h**4)
y1 = -0.2405 + 0.0296 * np.log10(ni2pfree)
y2 = 0.1102-0.0592*pH_x
interp1 = scipy.interpolate.InterpolatedUnivariateSpline(pH_x, y1)
interp2 = scipy.interpolate.InterpolatedUnivariateSpline(pH_x, y2)
def difference(pH_x):
return np.abs(interp1(pH_x) - interp2(pH_x))
x_at_crossing = scipy.optimize.fsolve(difference, x0=0.0)
plt.plot(x_at_crossing, interp1(x_at_crossing), 'cd', ms=7, label='fsolve method')
plt.show()
1条答案
按热度按时间ctzwtxfj1#
函数
least_squares()
期望第一个参数fun
具有签名fun(x, *args,**kwargs)
,其中参数x
是形状为(n,)
的ndarray,而在本例中,它具有形状(2,100)
。此错误是由于您
return
函数equation()
的方式引起的:return (n_total-nh3-4*nin4p2-6*nin6p2-nh4, ni_total - ni2pfree - nin4p2- nin6p2- nio2)
返回形状为(2,)
的tuple
,而不是形状为(n,)
的数组。将您的
return
行更改为:return np.array([n_total-nh3-4*nin4p2-6*nin6p2-nh4, ni_total - ni2pfree - nin4p2- nin6p2- nio2]).flatten()
个允许代码完全运行,但我相信您得到的答案是不正确的,因为此“解决方案”只将形状为
(2,100)
的数组扁平化为形状为(n,)
。