如何求解不同初始条件的微分方程
How to solve a differential equation for different initial conditions
我想通过改变初始条件连续求解一个微分方程。我已经尝试了很多,但没有找到任何合适的过程来正确地做到这一点。任何人都可以分享任何想法吗?为了您的考虑,我在下面给出了可以求解微分方程的代码:
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
列表的格式正确即可循环。使用函数,您还可以指定对 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()
我想通过改变初始条件连续求解一个微分方程。我已经尝试了很多,但没有找到任何合适的过程来正确地做到这一点。任何人都可以分享任何想法吗?为了您的考虑,我在下面给出了可以求解微分方程的代码:
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
列表的格式正确即可循环。使用函数,您还可以指定对 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()