Search code examples
pythonscipydifferential-equationsnonlinear-functions

Solving differential equation using scipy.integrate.odeint: "Result from function call is not a proper array of floats."


I am working on drawing a graph of this non-linear first-order differential equation:

dv/dt + 3 v**2 + 2 = 0

Here is the code:

from scipy.integrate import odeint

from matplotlib import pyplot as plt

import numpy as np

def diff(v, t):

      return [v, -3*v*v - 2]

t = np.arange(-1,1,0.01)

v0 = 1

f = odeint(diff, v0, t)

plt.figure(figsize=(5,5))

plt.plot(t, f)

plt.show()

However, this does not work:

odepack.error: Result from function call is not a proper array of floats.


Solution

  • The odeint routine expects the first parameter to calculate the derivative only:

    func : callable(y, t0, …)
    Computes the derivative of y at t0.

    However, your function diff returns a 2-element list containing the solution in addition to the derivative:

    def diff(v, t):
    
          return [v, -3*v*v - 2]
    

    To fix this you simply need to remove v from the return value and avoid wrapping it in a list:

    def diff(v, t):
    
          return -3*v*v - 2