I am solving a system of coupled differential equations, with one of the "constant" in the differential equations is actually a periodically changing value: first half of the period has the value of 1 and the rest of the period have the value of 0, and the period is 2pi.
I was setting the value of that constant as a square function(used square function code and if else codes), and solving the differential equation with odeint.
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
import math
from scipy import signal
u=0.3
def l(f):
if int(2*t)%2np.pi == 0:
return 1
else:
return -1
def model(theta,t):
j = theta[0]
x = theta[1]
p = theta[2]
dJ_dt = 2*l(f)*(math.sqrt(2))*x*j
dX_dt = p-(k/2)*x
dP_dt = -x-(k/2)*p-2*l(f)*(math.sqrt(2))*j
dtheta_dt = [dJ_dt, dX_dt, dP_dt]
return dtheta_dt
theta_0 = [0.5*math.sqrt(1-u**2), 0, -0.5*u, 0, 0]
t = np.linspace(0,5000,1000)
theta = odeint(model,theta_0,t)
plt.figure(figsize=(25,8))
plt.plot(t, theta[:,0],label='j')
plt.legend(fontsize=15)
plt.xlabel('Time', fontsize= 30)
plt.xticks(fontsize= 20)
plt.ylabel('jx', fontsize= 30)
plt.yticks(fontsize= 20)
plt.show()
But seems that since the constant is not a "scalar", the code is not solvable.
I have also consult this post: Plotting solved ordinary differential equations over changing constant values but the method and the result is not what I want I out of solution and have no further idea how to include this periodic changing value and solve the system.
Or is that the odeint is not usable in this case?
Thanks in advance of any answer.
There are several things wrong from a pure python perspective in this function
def l(f):
if int(2*t)%2np.pi == 0:
return 1
else:
return -1
f
is not used in the function, instead an undeclared t
appears.2np.pi
should give an immediate syntactic error int(2*t)%2*np.pi
is (int(2*t)%2)*np.pi
, which is likely not the desired interpretation. Use int((2*f)%(2*np.pi))
. You can also cancel the 2-1
, while in the description you have 0
.model
is a system for 3 state components, your initial state has 5 components. That is not compatible.Please report a detailed error description, not just your summary of the observed error.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.