Skip to content

Commit d8684e4

Browse files
committed
RK4
Added RK4 integrator
1 parent b8f2bec commit d8684e4

3 files changed

Lines changed: 86 additions & 0 deletions

File tree

math/rk4/read.me

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
title: 4th Order Runge-Kutta
2+
date: 2025-12-09
3+
program: rk4.bas
4+
screenshot: rk4.bmp
5+
description: A 4th order Runga-Kutta integrator for solving ODEs. This intended to be loaded into the library and used that way. The subroutine works in-place, filling an output array(n,m) with the answer for an n dimensional problem with m timesteps. The screenshot is from an example, solving the ode f(t,y) = -y.

math/rk4/rk4.bas

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
/* Runge-Kutta 4th Order ODE Integrator
2+
3+
Integrates the ODE system using RK-4
4+
with a fixed step size.
5+
6+
Arguments:
7+
fname$ - function name of rhs of od
8+
function signature must
9+
follow
10+
fn(t,y(),o())
11+
where the result is returned
12+
in-place in the array o
13+
function returns 1 for success
14+
and 0 to terminate integration
15+
y0(n) - array of initial conditions
16+
t0 - initial value of t
17+
dt - fixed time step
18+
o(n,m) - pre-allocated output array
19+
n variables
20+
m timesteps
21+
*/
22+
Sub rk4 fname$,y0(),t0,dt,o()
23+
'check bounds of arrays
24+
Local integer l = Bound(o(),0)
25+
Local integer n = Bound(o(),1)
26+
Local integer m = Bound(o(),2)
27+
28+
If Bound(y0(),0) <> l Then
29+
Error "y0 and o must start at the same index"
30+
End If
31+
32+
If Bound(y0(),1) <> n Then
33+
Error "array size mismatch"
34+
End If
35+
36+
'initialize loop variables
37+
Local integer i,j,flag
38+
Dim float k1(n),k2(n),k3(n),k4(n)
39+
Dim float yi(n),a(n)
40+
Dim float ti = t0
41+
Array Add y0(),0,yi()
42+
Array Insert o(),,l,y0()
43+
44+
'main loop
45+
For i=l+1 To m
46+
Array Add yi(),0,a()
47+
flag = Call(fname$,ti,a(),k1())
48+
49+
'check flag and terminate early
50+
If flag=0
51+
Exit For
52+
End If
53+
54+
Math scale k1(),0.5*dt,a()
55+
Math c_add yi(),a(),a()
56+
flag = Call(fname$,ti+0.5*dt,a(),k2())
57+
58+
Math scale k2(),0.5*dt,a()
59+
Math c_add yi(),a(),a()
60+
flag = Call(fname$,ti+0.5*dt,a(),k3())
61+
62+
Math scale k3(),dt,a()
63+
Math c_add yi(),a(),a()
64+
flag = Call(fname$,ti+dt,a(),k4())
65+
66+
Math scale k1(),dt/6,k1()
67+
Math scale k2(),dt/3,k2()
68+
Math scale k3(),dt/3,k3()
69+
Math scale k4(),dt/6,k4()
70+
71+
Array Set 0,a()
72+
Math c_add yi(),k1(),a()
73+
Math c_add a(),k2(),a()
74+
Math c_add a(),k3(),a()
75+
Math c_add a(),k4(),a()
76+
77+
ti = ti+dt
78+
Array Add a(),0,yi()
79+
Array Insert o(),,i,yi()
80+
Next i
81+
End Sub

math/rk4/rk4.bmp

300 KB
Binary file not shown.

0 commit comments

Comments
 (0)