Python中Runge-Kutta的方法

Method of Runge-Kutta in Python

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

这是我的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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的示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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]

如果程序的微分方程计算全部,我该怎么办?


您必须将等式输入代码移出函数f(x,y)

要求在同一个块中输入方程式,就像要求所有其他输入一样。

因为它代表您的代码在每个时间间隔调用函数,因此将在每个时间间隔请求输入。


如果我不理解,请纠正我。
您是否尝试通过用户手动输入表达式并将其视为函数?
我找到了这个主题,它解释了如何使用sympy解析公式。 您可以尝试使用sympy修改您的程序。 通过这种方式,您应该能够为所有人获得一次方程式。

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