繁体   English   中英

从ODE求解器调用非线性方程求解器时,解决不匹配形状误差

[英]fsolve mismatch shape error when nonlinear equations solver called from ODE solver

我的函数“ par_impl(y)”内部有一个由两个非线性方程组成的系统,可以单独使用scipy.optimize.root进行求解。 这里的“ y”是一个参数。 但是我希望从ODE求解器odeint调用此系统,以便针对不同的“ y”值与简单的ODE耦合来求解该系统。 这使我解决了形状不匹配的错误。

将numpy导入为np

从scipy.optimize导入根导入

matplotlib.pyplot作为plt

从scipy.integrate导入odeint

def par_impl(y):

 def functionh(x): return [y + (x[0]**2) - x[1] -23, -4 - y*x[0] + (x[1]**2)] sol = root(functionh, [1, 1]) return sol.x 

def dy_dt(y,t):

 dydt = (y**0.5) + par_impl(y)[0] return dydt 

ls = np.linspace(0,2,50)y_0 = 2

Ps = odeint(dy_dt,y_0,ls)

y = Ps [:,0]

plt.plot(ls,y,“ +”,label =“ X”)plt.legend(); plt.figure()

我得到的错误是:

_check_func中的文件“ C:\\ Users \\ matteo \\ AppData \\ Local \\ Continuum \\ anaconda3 \\ lib \\ site-packages \\ scipy \\ optimize \\ minpack.py”第41行,引发TypeError(msg)

TypeError:fsolve:'func'参数'functionh'的输入和输出形状不匹配,形状应为(2,)但应为(2,1)。

问题是y是代码中len = 1的列表。 要访问其元素,您需要在函数中使用y[0] 下面是带有输出图的代码的工作版本(未显示整个代码)。

from scipy.optimize import root
from scipy.integrate import odeint
# Other plotting and numpy imports

def par_impl(y):
    def functionh(x):
        return [y[0] + (x[0]**2) - x[1] -23, -4 - y[0]*x[0] + (x[1]**2)] # y --> y[0]
    sol = root(functionh, ([1, 1]))
    return sol.x

# dy_dt function here  

# Rest of your code unchanged

plt.plot(ls, y, "+", label="X") 
plt.legend()

产量

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM