Using numpy, sympy, scipy, Solve the second-order ordinary differential equation under the initial conditions.
Problem (simple vibration): ($ k = 1 $ is a parameter) $ x'' (t) + kx (t) = 0 $, initial condition $ x (0) = 0, x'(0) = 1 $
In Problem of first-order ordinary differential equations, the initial conditions are given numerically, but in the solution of second-order and higher-order ordinary differential equations, ** initial conditions are listed. Note that give in **.
from sympy import * #Imoprt all features from the sympy library
import numpy as np #import numpy with the name np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
"""
Second-order differential equation
example(Simple vibration): d^2x/dt^2 = -kx x(0)=0,x'(0)=Solve under the initial condition of 1
"""
#Symbol definition
x=Symbol('x') #letter'x'Is defined as the variable x
t=Symbol('t') #letter't'Is defined as the variable t
k=Symbol('k') #letter'k'Is defined as the variable k. In this question, it is used as a parameter.
#
def func2(x, t, k):
x1,x2=x
dxdt=[x2,-k*x1]
return dxdt
k = 1.0 #parameter settings
x0 = [0.0,1.0] #Initial conditions:Each x(0), x'(0)Represents
t=np.linspace(0,10,101) #Time step setting of integration:Divide 0 to 10 into 101 equal parts
sol2=odeint(func2, x0, t, args=(k,)) #Solve the differential equation numerically, x(t)And x'(t)The sol2 of the list[:,0]and[:,1]Store in ingredients.
#Visualization
plt.plot(t, sol2[:,0], linewidth=1,label='x(t)') # x(t)Illustrated
plt.plot(t, sol2[:,1], linewidth=1,label='dx(t)/dt') # dx/Illustrated dt
plt.xlabel('t', fontsize=18)
plt.ylabel('x', fontsize=18,rotation='horizontal')
plt.legend(loc='upper right')
plt.show()