Files
CalWay_Python/按方法整理/常微分方程-经典龙格-库塔格式.py
2025-06-17 00:07:14 +08:00

29 lines
1.1 KiB
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.

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}")