使用scipy.odeint求解微分方程遇数组大小不匹配RuntimeError求助
Hey there! Let's break down this error you're seeing—it's a common gotcha when working with odeint, and once you know what to look for, it's easy to fix.
What the Error Means
The error RuntimeError: The size of the array returned by func (1) does not match the size of y0 (3) is telling you exactly what's wrong:
- Your initial condition
initial_condiis a 3-element array (length 3). - But the differential equation function you passed to
odeintis only returning a 1-element array.odeintexpects the function to return a derivative value for every variable in your initial condition—so if you start with 3 variables, your function needs to return 3 derivatives.
Common Fixes to Try
1. Check Your Differential Equation Function
Let's say your initial condition is something like initial_condi = [x0, y0, z0] (3 variables: x, y, z). Your function must calculate and return the derivative of each variable (dx/dt, dy/dt, dz/dt) as a 3-element list/array.
Example of a wrong function (causes your error):
def bad_ode_func(y, t): x, y, z = y # Only returns one derivative instead of three return x + y
Example of a correct function:
def good_ode_func(y, t): x, y, z = y # Calculate derivative for each variable dxdt = x + y dydt = y - z dzdt = x * z # Return all three derivatives in a list/array return [dxdt, dydt, dzdt]
2. Verify Your Initial Condition's Size
Double-check that initial_condi is indeed a 3-element array. Sometimes typos happen—for example, accidentally writing initial_condi = [5] instead of initial_condi = [1, 2, 3]. You can quickly confirm with:
print(len(initial_condi)) # Should output 3
3. Confirm Your odeint Call
Make sure you're calling odeint in the right order:
# Correct order: function, initial condition, time points solution = odeint(your_ode_func, initial_condi, time_array)
Mixing up parameters (like swapping initial condition and time array) can sometimes cause weird size issues, though this usually throws a different error—it's still worth a quick check!
If you can share the full code for your ODE function and initial condition, we can pinpoint the exact line causing the mismatch. But based on the error message, the root cause is almost certainly a mismatch between the number of derivatives your function returns and the number of variables in your initial condition.
内容的提问来源于stack exchange,提问作者Usman YousafZai

