Last active
June 7, 2024 16:36
-
-
Save carlosal1015/a0cc838b469c751f75c69aa9aa8b6feb to your computer and use it in GitHub Desktop.
Euler method and Runge Kutta 4 Burden example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
r""" | |
Euler method 5.9 | |
w(0) = alpha | |
w(i + 1) = w(i) + h * f(t_i, w(i)) | |
w(0 + 1) = w(0) + h * f(t_0, w(0)) | |
t_0 = a + 0 * h = a | |
t_i = a + i * h, i = 0,..., N | |
""" | |
a = 0 | |
b = 2 | |
h = 1 / 2 | |
N = int((b - a) / h) | |
y0 = 0.5 | |
def f(t, y): | |
return y - t**2 + 1 | |
w = y0 # w0 | |
for i in range(1, N + 1): | |
w = w + h * f(a + (i - 1) * h, w) | |
print(w) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
r""" | |
Runge Kutta 4 | |
k1 = h * f(t, w) | |
k2 = h * f(t + h / 2, w + 1 / 2 * k1) | |
k3 = h * f(t + h / 2 , w + 1 / 2 * k2) | |
k4 = h * f(t + h, w + k3) | |
w = w + 1 / 6 * (k1 + 2*k2 + 2*k3 + k4) | |
""" | |
r"""" | |
Punto medio (Runge Kutta 2) | |
w = w + h * f(t + h / 2, h / 2 * f(t, w)) | |
""" | |
a = 0 | |
b = 2 | |
h = 1 / 5 | |
N = int((b - a) / h) | |
y0 = 0.5 | |
def f(t, y): | |
return y - t**2 + 1 | |
w = y0 # w0 | |
for i in range(1, N + 1): | |
t = a + (i - 1) * h | |
k1 = h * f(t, w) | |
k2 = h * f(t + h / 2, w + 1 / 2 * k1) | |
k3 = h * f(t + h / 2, w + 1 / 2 * k2) | |
k4 = h * f(t + h, w + k3) | |
w = w + 1 / 6 * (k1 + 2 * k2 + 2 * k3 + k4) | |
print(w) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment