使用scipy.integrate.odeint求解微分方程组时报ndim=2错误如何解决
报错原因与解决方案
RuntimeError: The array return by func must be one-dimensional, but got ndim=2 是因为你的微分方程函数rxn1返回的数组维度不符合要求,具体问题出在两处:
- 代码中存在未定义的变量
f:你在计算C0和微分方程表达式时都调用了f,但没有提前为f赋值。如果f被误定义为多维数组,后续和其他变量运算后会让返回的np.array维度升高,变成二维数组,触发报错。 - 原代码仅导入了
scipy.stats,没有导入scipy.integrate,直接调用scipy.integrate.odeint也会触发额外的属性错误。
你要的基于np.array的可运行修正代码如下:
import numpy as np import scipy.integrate import matplotlib.pyplot as plt # 此处f为示例赋值,可替换为你的实际参数值 f = 0.1 f_ini = [0.09, 0.09] C0 = 0.083 / f k = 0.04 v = 1.05 def rxn1(C, t): return np.array([f*C0/v - f*C[0]/v - k*C[0], f*C[0]/v - f*C[1]/v - k*C[1]]) t_points = np.linspace(0, 500, 1000) c_points = scipy.integrate.odeint(rxn1, f_ini, t_points) plt.plot(t_points, c_points[:,0], label='组分1浓度') plt.plot(t_points, c_points[:,1], label='组分2浓度') plt.legend() plt.xlabel('时间') plt.ylabel('浓度') plt.show()
只要你所有参数都是标量,上述代码返回的np.array天然是符合odeint要求的一维结构,可正常运行得到计算结果。
内容的提问来源于stack exchange,提问作者Ariunbilig Choijilsuren
相关产品推荐
相关产品推荐

