我正在实现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
然后我在这个系统上测试它:
^{pr2}$它似乎运行良好(我还用不同的初始值和不同的函数对其进行了测试:一切正常):
x10 = 1
x20 = 1
T = 1
h = 10
x1, x2 = cauchy(f1, f2, x10, x20, T, h)
t = np.linspace(0, T, h)
plt.xlabel('t')
plt.ylabel('x1')
plt.plot(t, true_x1(t), "blue", label="true_x1")
plt.plot(t, x1, "red", label="approximation_x1")
plt.legend(bbox_to_anchor=(0.97, 0.27))
plt.show()
plt.xlabel('t')
plt.ylabel('x2')
plt.plot(t, true_x2(t), "blue", label="true_x2")
plt.plot(t, x2, "red", label="approximation_x2")
plt.legend(bbox_to_anchor=(0.97, 0.97))
plt.show()
然后我想检查错误是否是O(step^4)
的顺序,所以我减少了步骤和计算错误,如下所示:
step = []
x1_error = []
x2_error = []
for segm in reversed(range(10, 1000)):
x1, x2 = cauchy(f1, f2, x10, x20, T, segm)
t = np.linspace(0, T, segm)
step.append(1/segm)
x1_error.append(np.linalg.norm(x1 - true_x1(t), np.inf))
x2_error.append(np.linalg.norm(x2 - true_x2(t), np.inf))
我明白了:
plt.plot(step, x1_error, label="x1_error")
plt.plot(step, x2_error, label="x2_error")
plt.legend()
所以,误差是线性的。这真的很奇怪,因为它应该是O(step^4)
的顺序。谁能告诉我我做错了什么吗?在
这将从
1
迭代到h-1
。由于缺少最后一步,从时间T-T/h
到时间T
的精确解的差是O(T/h)
。在因此使用
^{pr2}$对于从}的
i-1
到{h
步骤,或对于}。在
h
步骤,从i
到{另外,},结果是
np.linspace(0,1,4)
将产生4
等间距数字,其中第一个是0
,最后一个是{这可能不是你所期望的。所以用上面的修正使用
在两个计算中使用相同的时间点。在
如果使用通常意义上的字母,那么遵循代码会更容易,其中}是步长,
h
或{N
是步骤数。然后在循环h=T/N
或dt=T/N
之前定义,以避免在函数调用中重复使用T/N
。在相关问题 更多 >
编程相关推荐