Search code examples
pythonodeodeint

How do I deal with a 2nd Order ODE? Python: "TypeError: cannot unpack non-iterable float object"


I am currently trying to solve a 2nd Order Ordinary Differential Equation (ODE) by decomposing it into two 1st Order ODEs.

Problem Description Image

The equation involves variables x, v, and constants c1, c2, c3, c4. I am using the odeint function from the scipy.integrate library to solve the ODE numerically. However, I encounter the following error:

I already decomposed it as two 1st Order ODE. But Im having the following error when I try to solve it:

TypeError: cannot unpack non-iterable float object

c2 = 2 
c3 = 3 
c4 = 4

def dSdx(S, x):
    x, v = S
    return [v,
           k - c1*v-c2*x - c3*np.sin(m.radians(x)) + c4* np.cos(m.radians(x)) ]
x_0 = 0
v_0 = 0
S_0 = (x_0, v_0)

t = np.linspace(0, 0.3, 100)
sol = odeint(dSdx, y0=S_0, t=t, tfirst=True)

and with that I get this error that I cant understand:

----> 2     x, v = S
      3     return [v,
      4            k - c1*v-c2*x - c3*np.sin(m.radians(x)) + c4* np.cos(m.radians(x)) ]

TypeError: cannot unpack non-iterable float object```

Solution

  • The problem lies with your argument to odeint of tfirst=True.

    If you include this (non-default) value then you are assuming that dSdx has signature dSdx(t,S) - i.e. "the t comes first" - whereas it actually has signature dSdx(S,t) (or should have, anyway: you seem to have christened the second argument x). Your error message refers to the fact that it was trying to unpack the independent variable t, rather than the tuple S.

    Just omit tfirst=True in the call to odeint and use function signature def dSdx(S,t): in the derivative function.