求解和绘制不同常数值的方程

时间:2019-07-11 03:02:29

标签: loops numpy matplotlib scipy iteration

我已经通过使用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的不同值的方程式?

2 个答案:

答案 0 :(得分:2)

获得所需内容的一种方法是将代码包装在指定n的函数中。然后使用for循环遍历指定的n列表,然后在循环结束后获取图形。

import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint


def solveit(n=1):

    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], label='For n = %s'%n) #plot the curve and label n



#List of n to loop through        
ns= [1.,2.,3.,4.,5.]

fig = plt.figure() #declare fig

for n_ in ns:
    solveit(n_) #the function will plot curve for specified n

plt.legend(loc='best') #after loop add the legend and plot characteristics
plt.grid()
plt.show()

enter image description here

答案 1 :(得分:0)

创建一个包含要测试的所有n值的列表,然后为每个值调用函数