【问题标题】:Solving and plotting equation for different constant values求解和绘制不同常数值的方程
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    • 感谢您的评论。抱歉,因为我是 python 新手,所以你能解释一下我需要使用任何 for 循环然后为每个值调用函数吗? @leosteffen
    • 抱歉这里没有详细说明,我在手机上回复了。 @BenT 得到了它,所以我很高兴你得到了你想要的东西。
    • 不用担心,非常感谢您的努力。 @leosteffen
    【解决方案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()
    

    【讨论】:

    • 非常感谢@BenT。我预料到了这个结果,而你做到了。再次感谢。
    猜你喜欢
    • 2015-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-14
    • 1970-01-01
    • 1970-01-01
    • 2013-12-11
    • 1970-01-01
    相关资源
    最近更新 更多