-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathRunge-Kutta method
More file actions
46 lines (31 loc) · 813 Bytes
/
Runge-Kutta method
File metadata and controls
46 lines (31 loc) · 813 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# Python3 program to implement Runge
# Kutta method
# A sample differential equation
# "dy/dx = (x - y)/2"
def dydx(x, y) :
return (x + y - 2);
# Finds value of y for a given x
# using step size h
# and initial value y0 at x0.
def rungeKutta(x0, y0, x, h) :
# Count number of iterations
# using step size or
# step height h
n = round((x - x0) / h);
# Iterate for number of iterations
y = y0;
for i in range(1, n + 1) :
# Apply Runge Kutta Formulas
# to find next value of y
k1 = h * dydx(x0, y);
k2 = h * dydx(x0 + 0.5 * h, y + 0.5 * k1);
# Update next value of y
y = y + (1.0 / 6.0) * (k1 + 2 * k2);
# Update next value of x
x0 = x0 + h;
return y;
# Driver Code
if __name__ == "__main__" :
x0 = 0; y = 1;
x = 2; h = 0.2;
print("y(x) =",rungeKutta(x0, y, x, h));