Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 龙格–;库塔四阶方法_Python_Numerical Methods_Runge Kutta - Fatal编程技术网

Python 龙格–;库塔四阶方法

Python 龙格–;库塔四阶方法,python,numerical-methods,runge-kutta,Python,Numerical Methods,Runge Kutta,我正在为两个方程组实现Runge–Kutta四阶方法 h是段数,因此T/h是步长 def cauchy(f1, f2, x10, x20, T, h): x1 = [x10] x2 = [x20] for i in range(1, h): k11 = f1((i-1)*T/h, x1[-1], x2[-1]) k12 = f2((i-1)*T/h, x1[-1], x2[-1]) k21 = f1((i-1)*T/h

我正在为两个方程组实现Runge–Kutta四阶方法

h是段数,因此T/h是步长

def cauchy(f1, f2, x10, x20, T, h):
    x1 = [x10]
    x2 = [x20]

    for i in range(1, h):
        k11 = f1((i-1)*T/h, x1[-1], x2[-1])
        k12 = f2((i-1)*T/h, x1[-1], x2[-1])
        k21 = f1((i-1)*T/h + T/h/2, x1[-1] + T/h/2*k11, x2[-1] + T/h/2*k12)
        k22 = f2((i-1)*T/h + T/h/2, x1[-1] + T/h/2*k11, x2[-1] + T/h/2*k12)
        k31 = f1((i-1)*T/h + T/h/2, x1[-1] + T/h/2*k21, x2[-1] + T/h/2*k22)
        k32 = f2((i-1)*T/h + T/h/2, x1[-1] + T/h/2*k21, x2[-1] + T/h/2*k22)
        k41 = f1((i-1)*T/h + T/h, x1[-1] + T/h*k31, x2[-1] + T/h*k32)
        k42 = f2((i-1)*T/h + T/h, x1[-1] + T/h*k31, x2[-1] + T/h*k32)

        x1.append(x1[-1] + T/h/6*(k11 + 2*k21 + 2*k31 + k41))
        x2.append(x2[-1] + T/h/6*(k12 + 2*k22 + 2*k32 + k42))

    return x1, x2
然后我在这个系统上测试它:

它似乎工作正常(我还用不同的初始值和不同的函数对它进行了测试:一切正常):

然后我想检查错误的顺序是否为
O(步骤^4)
,因此我减少步骤并计算如下错误:

我明白了:

plt.plot(step, x1_error, label="x1_error")
plt.plot(step, x2_error, label="x2_error")
plt.legend()

因此,从步长开始,误差是线性的。这真的很奇怪,因为它的顺序应该是
O(步骤^4)
。谁能告诉我我做错了什么

for i in range(1, h):
这将从
1
迭代到
h-1
。由于缺少最后一步,时间
T-T/h时的
x[h-1]
与时间
T
时的精确解之间的差异是
O(T/h)

因此使用

for i in range(1,h+1):
对于
h
i-1
i
的步骤,或

for i in range(h):
对于
h
i
i+1
的步骤


另外,
np.linspace(0,1,4)
将产生
4
等距数字,其中第一个是
0
,最后一个是
1
,从而产生

array([ 0.        ,  0.33333333,  0.66666667,  1.        ])
这可能不是你所期望的。因此,与上述更正一起使用

t = np.linspace(0, T, segm+1)
在两次计算中使用相同的时间点


如果您使用字母的通常含义,则更容易遵循代码,其中
h
dt
是步长,而
N
是步数。然后在循环之前定义
h=T/N
dt=T/N
,以避免在函数调用中重复使用
T/N

这将从
1
迭代到
h-1
。由于缺少最后一步,时间
T-T/h时的
x[h-1]
与时间
T
时的精确解之间的差异是
O(T/h)

因此使用

for i in range(1,h+1):
对于
h
i-1
i
的步骤,或

for i in range(h):
对于
h
i
i+1
的步骤


另外,
np.linspace(0,1,4)
将产生
4
等距数字,其中第一个是
0
,最后一个是
1
,从而产生

array([ 0.        ,  0.33333333,  0.66666667,  1.        ])
这可能不是你所期望的。因此,与上述更正一起使用

t = np.linspace(0, T, segm+1)
在两次计算中使用相同的时间点



如果您使用字母的通常含义,则更容易遵循代码,其中
h
dt
是步长,而
N
是步数。然后在循环之前定义
h=T/N
dt=T/N
,以避免在函数调用中重复使用
T/N

谢谢,这很有帮助!谢谢,这很有帮助!