Using numpy, sympy, scipy, Solve the first-order ordinary differential equation under the initial conditions.
problem: $ x'(t) + k x (t) = 0 $, initial condition $ x (0) = 1 $, (k = 1 is a parameter)
The exact solution is $ x (t) = e ^ {-t} $.
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
"""
example:First-order ordinary differential equation:
dx/dt = -kx x(0)=Solve under the initial condition of 1
"""
x=Symbol('x') #letter'x'Is defined as the variable x
y=Symbol('y') #letter'y'Is defined as the variable y
t=Symbol('t') #letter't'Is defined as the variable y
k=Symbol('k')
def func(x, t, k): # dx/Define dt as a function
dxdt=-k*x
return dxdt
k = 1.0 #Set the value to the parameter
x0 = 1.0 #Initial conditions
t=np.linspace(0,10,101) #Time step setting of integration:Divide 0 to 10 into 101 equal parts
sol=odeint(func, x0, t, args=(k,)) #Solve the differential equation numerically. Store the results in a list called sol.
#Exact solution for comparison(e^-t)List excact_Set to sol
exact_sol=[]
tt=np.linspace(0,10,101)
for i in tt:
exact_sol.append(exp(-1.0*float(i)))
#
#Visualization
plt.plot(t, sol, linewidth=1,label='numerical') #Numerical solution
plt.plot(tt, exact_sol, color='red',linewidth=1, label='exact') #True solution
plt.xlabel('t', fontsize=18)
plt.ylabel('x', fontsize=18,rotation='horizontal')
plt.legend(loc='upper right')
plt.show()