首页 文章

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

提问于
浏览
0

我的函数“par_impl(y)”中有两个非线性方程组,我可以使用scipy.optimize.root独立解决 . 这里“y”是一个参数 . 但我希望从ODE求解器odeint中调用这个系统,以便为“y”的不同值求解它,并与简单的ODE相结合 . 这给了我fsolve不匹配形状错误 .

从scipy.optimize import root import matplotlib.pyplot从scipy.integrate import odeint def par_impl(y):import functionh(x):import numpy as np from scipy.optimize import root import matplotlib.pyplot
return [y(x [0] ** 2) - x [1] -23,-4 - y * x [0](x [1] ** 2)]
sol = root(functionh,[1,1])

返回sol.x
def dy_dt(y,t):dydt =(y ** 0.5)par_impl(y)[0]

返回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()

我得到的错误是:

文件“C:\ Users \ matteo \ AppData \ Local \ Continuum \ anaconda3 \ lib \ site-packages \ scipy \ optimize \ minpack.py”,第41行,在_check_func中引发TypeError(msg)TypeError:fsolve:有一个'func'参数'functionh'的输入和输出形状之间不匹配 . 形状应为(2,),但它是(2,1) .

1 回答

  • 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()
    

    Output

    enter image description here

相关问题