Search code examples
pythonscipyode

Ode solver in python


I am trying to solve an ODE (dx^2/dt^2 = -4(x^2+y^2)^(3/2)) using scipy odeint, but I can't get it to work. Here is my code:

import numpy as np
from scipy.integrate import odeint

def system(x,t,y):
    x1 = x[0]
    x2 = x[1]
    y1 = y

    dx1_dt = x2
    dx2_dt = -4*(x1**2+y1**2)**(3/2)
    dx_dt = [dx1_dt,dx2_dt]

    return dx_dt


x_0 = [2,3]
y_0 = [8,6]

t = np.linspace(0,1,30)
x_solved = odeint(system,x_0,t,args=(y_0[0]))

I am getting this error:

odepack.error: Extra arguments must be in a tuple

But I am passing the extra arguments as a tuple: args=(y_0[0]). What am i doing wrong? Thank you!


Solution

  • A tuple with single element should be in the format (y_0[0],). Note the comma.

    (x) evaluates to x
    (x,) evaluates to a tuple with one element

    ( ) are often used for syntactic and better readability reasons.
    is_true = (x and y) or (a or k)

    Since ( ) are already used for creating tuples, the way to differentiate a single element tuple and an expression is that comma.