Reputation: 77
I'm triying to write an ode to solve an harmonic oscillator problem and I have this problem with my function harmonic to use in odeint command.
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import odeint
k=4.0
m=1.0
B=0
def harmonic((x, y), t):
return [y, -k * x / m + B / m * y]
Gives the error message:
File "<ipython-input-60-2d6b156227be>", line 1
def harmonic((x, y), t):
^
SyntaxError: invalid syntax
Someone can help me? Thank you!
Upvotes: 1
Views: 1079
Reputation: 1672
Look at the following example:
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import odeint
k = 4.0
m = 1.0
B = 0
def harmonic(var, t=None):
x, y = var[0], var[1] # var is assumed to be an array, usually numpy array
return [y, -k * x / m + B / m * y]
result = odeint(harmonic, (0.2, 0), np.linspace(0, 1, 100))
plt.plot(result[:,0], result[:,1], 'r-')
plt.show()
Upvotes: 2
Reputation: 5473
(x, y)
represents a tuple. If you want to just use x,y as individual variables, simply use x,y
. Your function will look like this:
def harmonic(x, y, t):
return [y, -k * x / m + B / m * y]
Passing hypothetical values for x,y & t to the harmonic function returns the list calculated by the code in the return
statement of the function:
harmonic(2,3,5)
#Output:
[3, -8.0]
Upvotes: 1