How to resolve the algorithm Runge-Kutta method step by step in the Nim programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Runge-Kutta method step by step in the Nim programming language
Table of Contents
Problem Statement
Given the example Differential equation: With initial condition: This equation has an exact solution:
Demonstrate the commonly used explicit fourth-order Runge–Kutta method to solve the above differential equation.
Starting with a given
y
n
{\displaystyle y_{n}}
and
t
n
{\displaystyle t_{n}}
calculate: then:
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Runge-Kutta method step by step in the Nim programming language
Source code in the nim programming language
import math
proc fn(t, y: float): float =
result = t * math.sqrt(y)
proc solution(t: float): float =
result = (t^2 + 4)^2 / 16
proc rk(start, stop, step: float) =
let nsteps = int(round((stop - start) / step)) + 1
let delta = (stop - start) / float(nsteps - 1)
var cur_y = 1.0
for i in 0..(nsteps - 1):
let cur_t = start + delta * float(i)
if abs(cur_t - math.round(cur_t)) < 1e-5:
echo "y(", cur_t, ") = ", cur_y, ", error = ", solution(cur_t) - cur_y
let dy1 = step * fn(cur_t, cur_y)
let dy2 = step * fn(cur_t + 0.5 * step, cur_y + 0.5 * dy1)
let dy3 = step * fn(cur_t + 0.5 * step, cur_y + 0.5 * dy2)
let dy4 = step * fn(cur_t + step, cur_y + dy3)
import math, strformat
proc fn(t, y: float): float =
result = t * math.sqrt(y)
proc solution(t: float): float =
result = (t^2 + 4)^2 / 16
proc rk(start, stop, step: float) =
let nsteps = int(round((stop - start) / step)) + 1
let delta = (stop - start) / float(nsteps - 1)
var cur_y = 1.0
for i in 0..<nsteps:
let cur_t = start + delta * float(i)
if abs(cur_t - math.round(cur_t)) < 1e-5:
echo &"y({cur_t}) = {cur_y}, error = {solution(cur_t) - cur_y}"
let dy1 = step * fn(cur_t, cur_y)
let dy2 = step * fn(cur_t + 0.5 * step, cur_y + 0.5 * dy1)
let dy3 = step * fn(cur_t + 0.5 * step, cur_y + 0.5 * dy2)
let dy4 = step * fn(cur_t + step, cur_y + dy3)
cur_y += (dy1 + 2 * (dy2 + dy3) + dy4) / 6
rk(start = 0, stop = 10, step = 0.1)
cur_y += (dy1 + 2.0 * (dy2 + dy3) + dy4)
You may also check:How to resolve the algorithm Longest string challenge step by step in the FutureBasic programming language
You may also check:How to resolve the algorithm Chinese zodiac step by step in the C programming language
You may also check:How to resolve the algorithm Here document step by step in the NMAKE.EXE programming language
You may also check:How to resolve the algorithm Loops/For step by step in the Nemerle programming language
You may also check:How to resolve the algorithm Long multiplication step by step in the NetRexx programming language