【问题标题】:error: The array return by func must be one-dimensional, but got ndim=2错误:func返回的数组必须是一维的,但得到ndim=2
【发布时间】:2022-06-21 01:59:45
【问题描述】:

我正在尝试使用 odeint 在 python 中解决一个简单的 ODE,但输出始终是我在输入数组中有更多维度。我查了一下,没发现问题

Error output

蓝色的,是我要解的方程 ode i want to solve

这是我的代码

from scipy.integrate import odeint
import matplotlib.pyplot as plt
import numpy as np

y0 = [1]
th = np.linspace(-180,180)

def pend(y,th):
    r=10
    a = 5; # Weibe efficiency factor
    n = 3; # Weibe form factor
    ths = -20; # start of combustion  º
    thd = 60; # duration of combustion º 
    gamma = 1.4
    q = 34.8
    #state variables
    P = y
    
    #define volume 
    vol = (1 + (r-1)/2*(1 - np.cos(th*np.pi/180)))/r
    dvol = (r-1)/2*np.sin(th*np.pi/180)/r
    
    #definimos para la fracción de masa
    dum =(th-ths)/thd; 
    if th > ths:
        temp = -a*dum**n
        x= 1 -np.exp(temp)
        dx =n*a*(1-x)*dum**(n-1) 
    else:
        dx = 0
    
    dP = -gamma*P/vol*dvol + (gamma - 1)*q/vol*dx
    
    #vector con las primeras derivadas de las variables de estado
    dydth = [dP]
    return dydth

sol = odeint(pend, y0, th)
plt.close()
plt.plot(th, sol[:, 0], 'b')
plt.grid()
plt.show()

如果有人愿意帮助我,我会很感激的

【问题讨论】:

    标签: python python-3.x ode differential-equations odeint


    【解决方案1】:

    您永远不会解压缩输入数组,例如 P=y[0]。因此,所有P 的计算都是作为数组操作完成的,最后的dP 是一个数组。当你再次将它打包为数组时,你会得到一个维度为 2 的数组。

    不过,这只适用于第一个分支,在第二个分支中dx=0 只是一个标量。但是将标量升级为简单数组是由 odeint 接口自动完成的,因此不应提供错误

    【讨论】:

      【解决方案2】:

      当你用括号定义 dydth 时,它会将 ndim 更改为 2

      交换返回 (dP),或者让 dydth = (dP) 然后返回 dydth

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-01-27
        • 1970-01-01
        • 1970-01-01
        • 2020-05-24
        • 1970-01-01
        • 1970-01-01
        • 2015-01-06
        • 1970-01-01
        相关资源
        最近更新 更多