rungego-kutty dodane

This commit is contained in:
2024-12-27 21:38:06 +01:00
parent 9f3aed89f6
commit 2c23dba6e6

View File

@@ -0,0 +1,33 @@
import numpy as np
x0 = 1.7
xk = 2.7
h = 0.1
y0 = 5.3
def f(x, y):
return x**2 + np.cos(y / np.pi)
def runge_kutta_4(f, x0, y0, h, xk):
n = int((xk - x0) / h) + 1
x = [x0 + i * h for i in range(n)]
y = [0] * n
y[0] = y0
print("Tabela wyników:")
print(f"{'i':<5}{'x':<10}{'y':<15}{'k1':<10}{'k2':<10}{'k3':<10}{'k4':<10}{'Δy':<10}")
for i in range(1, n):
k1 = h * f(x[i-1], y[i-1])
k2 = h * f(x[i-1] + h/2, y[i-1] + k1/2)
k3 = h * f(x[i-1] + h/2, y[i-1] + k2/2)
k4 = h * f(x[i-1] + h, y[i-1] + k3)
Δy = (k1 + 2*k2 + 2*k3 + k4) / 6
y[i] = y[i-1] + Δy
print(f"{i-1:<5}{x[i-1]:<10.2f}{y[i-1]:<15.5f}{k1:<10.5f}{k2:<10.5f}{k3:<10.5f}{k4:<10.5f}{Δy:<10.5f}")
print(f"{n-1:<5}{x[-1]:<10.2f}{y[-1]:<15.5f}")
return x, y
x, y = runge_kutta_4(f, x0, y0, h, xk)