Files
CalWay_Python/279-3.py
2025-06-10 14:27:18 +08:00

26 lines
610 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#经典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+4*k2+k3)/6
x0 += h
result.append((x0,y0))
return result
if __name__=="__main__":
x0 = 0
y0 = -1
fxy = lambda x,y: x + y
real_fx = lambda x: -x-1
h = 0.1
xk = 2
result = ClassicRK(x0, y0, h, xk, fxy)
print("x\ty\t\treal_y")
for x, y in result:
print(f"{x:.2f}\t{y}\t{real_fx(x)}")