Numerically solving initial value problem
Last edited at 2025-06-11
42 Views
(공학수학1 과제용)
Let's solve an initial value problem numerically with a computer.
We will compare the accuracy of three methods: Euler method, Improved Euler method, and Runge-Kutta method.
Problem
,
Source Code (Python)
x0 = 0.0
y0 = 0.0
h = 0.1
exact = 0.436563656918
def f(x,y):
return y + x**2
# (1) Euler method
x = x0
y = y0
for i in range(10):
Dy = f(x, y)
x += h
y += Dy*h
print("(1) Euler method")
print("y =", y)
print("e =", abs(y-exact))
# (2) Improved Euler method
x = x0
y = y0
for i in range(10):
Dy = f(x, y)
Dy2 = f(x + h, y + Dy*h)
x += h
y += (h/2) * (Dy + Dy2)
print("\n(2) Improved Euler method")
print("y =", y)
print("e =", abs(y-exact))
# (3) Runge-Kutta method
x = x0
y = y0
for i in range(10):
k1 = h*f(x,y)
k2 = h*f(x + h/2, y + k1/2)
k3 = h*f(x + h/2, y + k2/2)
k4 = h*f(x+h, y+k3)
x += h
y += (k1 + 2*k2 + 2*k3 + k4) / 6
print("\n(3) Runge-Kutta method")
print("y =", y)
print("e =", abs(y-exact))
Results
(1) Euler method y = 0.34685916621 e = 0.08970449070799996 (2) Improved Euler method y = 0.4363239829622023 e = 0.00023967395579765904 (3) Runge-Kutta method y = 0.43656289201769494 e = 7.649003050391734e-07