Reputation: 41
I want to solve a second order differential equation with GEKKO. In the documentation there is only an example that shows you how to solve a first order equation. I can't figure out how to write the second derivative of y to make it work.
This is the example from the documentation for a first order differential equation.
from gekko import GEKKO
import numpy as np
import matplotlib.pyplot as plt
m = GEKKO()
m.time = np.linspace(0,20,100)
k = 10
y = m.Var(value=5.0)
t = m.Param(value=m.time)
m.Equation(k*y.dt()==-t*y)
m.options.IMODE = 4
m.solve(disp=False)
plt.plot(m.time,y.value)
plt.xlabel('time')
plt.ylabel('y')
plt.show()
Upvotes: 4
Views: 1282
Reputation: 510
The first derivative can be declared as dy = y.dt()
and the second derivative as ddy = dy.dt()
import numpy as np
import matplotlib.pyplot as plt
m = GEKKO()
m.time = np.linspace(0,20,100)
k = 10
y = m.Var(value = 5.0)
t = m.Param(value=m.time)
dy = m.Var(value = 0.0)
ddy = m.Var(value = -5/10)
m.Equations([
k*y.dt()==-t*y,
dy == y.dt(),
ddy == dy.dt()
])
m.options.IMODE = 4
m.solve(disp=False)
plt.figure()
plt.plot(m.time,y.value, label = 'y')
plt.xlabel('time')
plt.plot(m.time, dy.value, label = 'dy')
plt.xlabel('time')
plt.plot(m.time, ddy.value, label = 'ddy')
plt.xlabel('time')
plt.legend()
plt.show()
You can find more information here : https://apmonitor.com/wiki/index.php/Apps/2ndOrderDifferential
Upvotes: 1