Search code examples
pythonpython-2.7scipyodedifferential-equations

Solution of differential equation on specific point python


I have a differential equation:

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

# function that returns dy/dt
def model(y,t):
   k = 0.3
   dydt = -k * y
   return dydt

# initial condition
y0 = 5

# time points
t = np.linspace(0,10)
t1=2
# solve ODE
y = odeint(model,y0,t)

And I want to evaluate the solution of this differential equation on two different points. For example I want y(t=2) and y(t=3).

I can solve the problem in the following way:

Suppose that you need y(2). Then you, define

t = np.linspace(0,2)

and just print

print y[-1]

In order to get the value of y(2). However I think that this procedure is slow, since I need to do the same again in order to calculate y(3), and if I want another point I need to do same again. So there is some faster way to do this?


Solution

  • isn't this just:

    y = odeint(model, y0, [0, 2, 3])[1:]
    

    i.e. the third parameter just specifies the values of t that you want back.

    as an example of printing the results out, we'd just follow the above with:

    print(f'y(2) = {y[0,0]}')
    print(f'y(3) = {y[1,0]}')
    

    which gives me:

    y(2) = 2.7440582441900494
    y(3) = 2.032848408317066
    

    which seems the same as the anytical solution:

    5 * np.exp(-0.3 * np.array([2,3]))