Mark Grace
Mark Grace

Reputation: 11

Python odeint clearly returning wrong solution

Using python 2.7.8.
The differential equation I'm working with is x'=2-3*x. Not that difficult. The correct solution is a decaying exponential with a y-intercept of 2/3. Exercise has three initial conditions. Also have to have a slope field with solution on the same plot. I have the slope field, but the solution provided is wrong. A test case of x'=x worked fine but only when t>0. But the solution odeint provided is wrong. Instead of a decaying exponential I'm given what looks like a trig function. Here is the code.

#Solutions function
def m_diff_sol(input_domain,input_initial_conditions_set):
    f_set=[]
    for n in input_initial_conditions_set:
        m_sol=odeint(m_fst_diff_eq,n,input_domain)
        f=[b for [a,b] in m_sol]
        f_set.append(f)
    return f_set

#Vector field function
def m_fst_diff_eq(x,t):
    m,mdot=x
    return [mdot,2-3*m]

enter image description here

Upvotes: 1

Views: 479

Answers (1)

Steve
Steve

Reputation: 1587

You want your ODE function to return 1 output, namely

def my_ode_func(x,t):
    return 2.0 - 3.0*x

Then odeint gives the expected exponential decay from the initial condition to x=2/3.

import numpy as np
from scipy.integrate import odeint
t = np.arange(0,10.0,0.01)
x0 = 1
out1 = odeint(my_ode_func,x0,t)

Numerical solution to linear ODE

It looks like you're instead modelling something like the second order ODE x''(t) = 2 - 3*x(t). This would be written as a system of first order ODEs Y(t) = [x(t),x'(t)], then

Y'(t) = [Y[2](t), 2 - 3*Y[1](t)]

The code would look something like this:

def my_ode_func2(Y,t):
    return [Y[1],2.0 - 3.0*Y[0]]

Y0 = [1,1]
out2 = odeint(my_ode_func2,Y0,t)

Numerical solution to second order ODE

Upvotes: 1

Related Questions