python - 如何求解不同初始条件的微分方程
问题描述
我想只通过改变初始条件来连续求解微分方程。我已经尝试了很多,但没有找到任何合适的过程来正确地做到这一点。任何人都可以分享任何想法。出于您的考虑,我在下面给出了可以求解微分方程的代码:
from scipy.integrate import odeint
import numpy as np
import matplotlib.pyplot as plt
c = 1.0 #value of constants
#define function
def exam(y, x):
theta, omega = y
dydx = [omega, - (2.0/x)*omega - theta**c]
return dydx
#initial conditions
y0 = [1.0, 0.0] ## theta, omega
x = np.linspace(0.1, 10, 100)
#call integrator
sol = odeint(exam, y0, x)
plt.plot(x, sol[:, 0], 'b')
plt.legend(loc='best')
plt.grid()
plt.show()
所以,我的问题是如何一次求解不同初始条件的上述微分方程(假设为y = [1.0, 0.0]
; y = [1.2, 0.2]
; y = [1.3, 0.3]
)并将它们绘制在一起。
解决方案
因此,您可以使用函数并遍历初始值。只需确保您的y0
s 列表格式正确即可循环。使用函数,您还可以指定对c
.
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
def solveit(c,y0):
def exam(y, x):
theta, omega = y
dydx = [omega, - (2.0/x)*omega - theta**c]
return dydx
#initial conditions
# y0 = [1.0, 0.0] ## theta, omega
x = np.linspace(0.1, 10, 100)
#call integrator
sol = odeint(exam, y0, x)
plt.plot(x, sol[:, 0], label='For c = %s, y0=(%s,%s)'%(c,y0[0],y0[1]))
ys= [[1.0, 0.0],[1.2, 0.2],[1.3, 0.3]]
fig = plt.figure()
for y_ in ys:
solveit(c=1.,y_)
plt.legend(loc='best')
plt.grid()
plt.show()