修改龙格库塔bug

This commit is contained in:
2025-06-17 00:07:14 +08:00
parent 08d293657d
commit fc0e7cec5f
7 changed files with 357 additions and 1 deletions

View File

@@ -0,0 +1,29 @@
import math
#经典R-K龙格-库塔法
def ClassicRK(x0,y0,h,xk,fxy):
k1=k2=k3=k4=0
result = [(x0,y0)]
while x0<=xk:
k1 = fxy(x0,y0)
k2 = fxy(x0+h/2,y0+h*k1/2)
k3 = fxy(x0+h/2,y0+h*k2/2)
k4 = fxy(x0+h,y0+h*k3)
y0 += h*(k1+2*k2+2*k3+k4)/6
x0 += h
result.append((x0,y0))
return result
if __name__=="__main__":
##########################################################################
x0 = 0 # x的初始值左边界换成题干里面的#################
y0 = -1 # y的初始值换成题干里面的#################
fxy = lambda x,y: x + y #f(x,y)换成题干里面的#################
real_fx = lambda x: -x-1 #真实函数换成题干里面的#################
h = 0.1 #步长换成题干里面的#################
xk = 2 #x的右边界换成题干里面的#################
result = ClassicRK(x0, y0, h, xk, fxy)
print("x\ty\t\treal_y\t\t\t误差")
for x, y in result:
print(f"{x:.2f}\t{y:.10f}\t\t{real_fx(x):.10f}\t\t\t{abs(y - real_fx(x)):.5f}")