我对Python非常陌生,并编写了以下代码来模拟弹簧摆的运动:
import numpy as np
from scipy.integrate import odeint
from numpy import sin, cos, pi, array
import matplotlib.pyplot as plt
init = array([0,pi/18,0,0])
def deriv(z, t):
x, y, dxdt, dydt = z
dx2dt2=(4+x)*(dydt)**2-5*x+9.81*cos(y)
dy2dt2=(-9.81*sin(y)-2*(dxdt)*(dydt))/(0.4+x)
return np.array([dxdt, dydt, dx2dt2, dy2dt2])
time = np.linspace(0.0,10.0,1000)
sol = odeint(deriv,init,time)
plt.xlabel("time")
plt.ylabel("y")
plt.plot(time, sol)
plt.show()
但它给出了x
、dxdt
、y
和dydt
的图,而不是dx2dt2
和dy2dt2
(分别是x
和y
的二阶导数)。我该如何修改我的代码来绘制二阶导数呢?你知道吗
odeint
的返回值是您定义为z = [x,y,x',y']
的z(t)
的解。因此,二阶导数不是odeint
返回的解的一部分。可以通过对一阶导数的返回值进行有限差分来近似x
和y
的二阶导数。你知道吗例如:
或者,由于您已经有了一个函数来计算解的二阶导数,您可以调用该函数:
相关问题 更多 >
编程相关推荐