如何在Python中绘制耦合的非线性二阶ODE的二阶导数?

时间:2018-12-13 20:30:22

标签: python numpy matplotlib differential-equations odeint

我是Python的新手,并编写了以下代码来模拟弹簧摆的运动:

|---------------------|------------------|------------------|
|      product_name   |     price        |   price_change   |
|---------------------|------------------|------------------|
|       Ibuprofen     |      30.20       |         0        |
|---------------------|------------------|------------------|
|       Ibuprofen     |      32.20       |         2        |
|---------------------|------------------|------------------|
|       Ibuprofen     |      35.20       |         3        |
|---------------------|------------------|------------------|

但这给了我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() xdxdt(而不是ydydtdx2dt2dy2dt2的二阶导数)。如何更改代码以绘制二阶导数?

1 个答案:

答案 0 :(得分:3)

odeint的返回值是您定义为z(t)的{​​{1}}的解决方案。因此,二阶导数不是z = [x,y,x',y']返回的解决方案的一部分。您可以通过对一阶导数的返回值进行有限差分来近似odeintx的二阶导数。

例如:

y

或者,由于您已经有一个函数可以从解中计算二阶导数,因此您可以调用该函数:

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)

x, y, xp, yp = sol.T

# compute the approximate second order derivative by computing the finite
# difference between values of the first derivatives
xpp = np.diff(xp)/np.diff(time)
ypp = np.diff(yp)/np.diff(time)

# the second order derivatives are now calculated at the midpoints of the
# initial time array, so we need to compute the midpoints to plot it
xpp_time = (time[1:] + time[:-1])/2

plt.xlabel("time")
plt.ylabel("y")
plt.plot(time, x, label='x')
plt.plot(time, y, label='y')
plt.plot(time, xp, label="x'")
plt.plot(time, yp, label="y'")
plt.plot(xpp_time, xpp, label="x''")
plt.plot(xpp_time, ypp, label="y''")
plt.legend()
plt.show()