【发布时间】:2019-11-20 16:38:00
【问题描述】:
我已经使用 odeint 求解了这个微分方程 (theta''(x) + (2/x) theta'(x) + theta^n = 0)。
from scipy.integrate import odeint
import numpy as np
import matplotlib.pyplot as plt
#value of constants
n = 1.0
#define function
def exam(y, x):
theta, omega = y
dydx = [omega, - (2.0/x)*omega - theta**n]
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', label='For n = 1')
plt.legend(loc='best')
plt.grid()
#plt.show()
###### (same procedure for n = 2) #########
#value of constants
n = 2.0
#define function
def exam(y, x):
theta, omega = y
dydx = [omega, - (2.0/x)*omega - theta**n]
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], 'g', label='For n = 2')
plt.legend(loc='best')
plt.grid()
plt.show()
虽然没有问题,但我得到了预期的结果。我只想知道是否有任何程序(如循环或其他)可以避免这种重复的程序,并且可以一次求解常数n 的不同值的方程?
【问题讨论】:
标签: loops numpy matplotlib scipy iteration