【问题标题】:Method of Runge-Kutta in PythonPython中的Runge-Kutta方法
【发布时间】:2015-07-30 08:37:37
【问题描述】:

我在python中写了一个runge-kutta方法的代码,但是每次程序实现任何微积分时,程序都需要微分方程。

这是我的代码:

from math import *
import numpy as np

#Initial Values
n=input("Enter the number of equations n:")
n=int(n)
x=np.array([])
for i in range(0,n):
    x0=input("Enter the initial value of x{}:".format(i))
    x=np.append(x,[x0])
t=input("Enter the initial value of t:")
tf=input("Enter the final value of t:")
h=input("Enter the time interval h:")
m=int((tf-t)/float(h))

#Definition of differential equations
def f(t,x):
    f=np.array([])
    for i in range(0,n):
        f0=input("Enter the equation f{}:".format(i))
        f=np.append(f,[f0])
    return f


a=1.0/6
for i in range(0,m): 
    k1=f(t,x)
    k2=f(t+0.5*h,x+0.5*h*k1)
    k3=f(t+0.5*h,x+0.5*h*k2)
    k4=f(t+h,x+h*k3)
    x=x+a*h*(k1+2*(k2+k3)+k4)
    t=t+h

print t, x

使用方程 dx/dt=x, x(0)=1, xf=1, h=0.1 的示例:

Enter the number of equations n:1
Enter the initial value of x0:1
Enter the initial value of t:0
Enter the final value of t:1
Enter the time interval h:0.1
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
Enter the equation f0:x[0]
1.0 [ 2.71827974]

我应该怎么做才能只输入一次微分方程来编程计算所有?

【问题讨论】:

    标签: python runge-kutta


    【解决方案1】:

    如果我不明白,请纠正我。 您是否试图获取用户手动输入的表达式并将其视为函数? 我找到了this topic,它解释了如何使用 sympy 解析公式。您可以尝试使用sympy 修改您的程序。通过这种方式,您应该能够一劳永逸地得到您的方程式。

    编辑:如果您的问题只是“如何从输入中获取整个公式...”,您可以尝试使用 raw_input() 方法。也看看here

    【讨论】:

    • 你必须问这是评论而不是回答
    • 我提供了两个答案,所以我认为我按下“答案按钮”没有错。谢谢你的建设性意见,顺便说一句。
    • 非常感谢,没想到用sympy。
    【解决方案2】:

    您必须将方程输入代码移出您的函数f(x,y)

    要求将方程式输入到您要求所有其他输入的同一块中。

    就目前而言,您的代码会在每个时间间隔调用该函数,因此会在每个时间间隔要求输入。

    【讨论】:

      猜你喜欢
      • 2014-07-27
      • 2023-02-18
      • 1970-01-01
      • 1970-01-01
      • 2019-04-14
      • 1970-01-01
      • 2018-08-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多