Angel Lira
Angel Lira

Reputation: 413

Multiple return using scipy.odeint method in Python

I am trying to use scipy.odeint() method in order to solve an second order partial derivative function.
I can do that for a single value of constant k, which is a constant of the function I have.
But I want to try this solution for many values of k.
To do so, I included the values that I want in a list k, and going through a loop I want to plug in these values for the final solution as arguments.
However, I am getting an error

error: Extra arguments must be in a tuple

import numpy as np
from scipy.integrate import odeint

### Code with a single value of K.THAT WORKS FINE!!!! ###
k = 1   #attributes to be changed
t = [0.1,0.2,0.3] #Data
init = [45,0] #initial values

#Function to apply an integration
def f(init, t, args=(k,)):
    dOdt = init[1]
    dwdt = -np.cos(init[0]) + k*dOdt
    return [dOdt, dwdt]

#integrating function that returns a list of 2D numpy arrays 
zCH = odeint(f,init,t)
################################################################
### Code that DOES NOT WORK!###
k = [1,2,3]   #attributes to be changed
t = [0.1,0.2,0.3] #Data
init = [45,0] #initial values

#Function to apply an integration
def f(init, t, args=(k,)):
    dOdt = init[1]
    dwdt = -np.cos(init[0]) + k*dOdt
    return [dOdt, dwdt]

solutions = []
for i in k:
    #integrating function that returns a list of 2D numpy arrays 
    zCH = odeint(f,init,t,(k[i-1]))
    solutions.append(zCH)```


    

Upvotes: 1

Views: 440

Answers (1)

DrBwts
DrBwts

Reputation: 3657

It has to do with the way you are passing k into your function f().

The following changes the value of k on each iteration

k_list = [1,2,3]       #attributes to be changed
t      = [0.1,0.2,0.3] #Data
init   = [45,0]        #initial values

#Function to apply an integration
def f(init, t, args=(k,)):
    dOdt = init[1]
    dwdt = -np.cos(init[0]) + k*dOdt
    return [dOdt, dwdt]

solutions = []
for k in k_list:
    #integrating function that returns a list of 2D numpy arrays 
    zCH = odeint(f, init, t)
    solutions.append(zCH)

Upvotes: 1

Related Questions