OISEAU
A modern DGTD framework
Loading...
Searching...
No Matches
rk4.hpp
1// Copyright (C) 2026 Tiago V. L. Amorim (@tiagovla)
2//
3// This file is part of oiseau (https://github.com/tiagovla/oiseau)
4//
5// SPDX-License-Identifier: GPL-3.0-or-later
6
7#pragma once
8
9#include <cmath>
10#include <stdexcept>
11#include <utility>
12
13#include "oiseau/time/detail/rhs.hpp"
14#include "oiseau/time/integrator.hpp"
15
16namespace oiseau::time {
17
19template <typename State, typename Rhs, typename AddScaled>
20void rk4_step(State& state, double time, double time_step, Rhs&& rhs, AddScaled&& add_scaled_fn) {
21 if (!std::isfinite(time)) {
22 throw std::invalid_argument("Time must be finite");
23 }
24 if (!std::isfinite(time_step) || time_step <= 0.0) {
25 throw std::invalid_argument("Time step must be finite and positive");
26 }
27
28 const auto k1 = rhs(time, state);
29 const auto stage2 = add_scaled_fn(state, k1, 0.5 * time_step);
30 const auto k2 = rhs(time + 0.5 * time_step, stage2);
31 const auto stage3 = add_scaled_fn(state, k2, 0.5 * time_step);
32 const auto k3 = rhs(time + 0.5 * time_step, stage3);
33 const auto stage4 = add_scaled_fn(state, k3, time_step);
34 const auto k4 = rhs(time + time_step, stage4);
35
36 auto output = add_scaled_fn(state, k1, time_step / 6.0);
37 output = add_scaled_fn(output, k2, time_step / 3.0);
38 output = add_scaled_fn(output, k3, time_step / 3.0);
39 output = add_scaled_fn(output, k4, time_step / 6.0);
40 state = std::move(output);
41}
42
44class RK4 {
45 public:
46 template <typename System, AddScaledState State>
47 static void step(System& system, State& state, double time, double time_step) {
48 rk4_step(
49 state, time, time_step,
50 [&system](double stage_time, const State& value) {
51 return detail::evaluate_rhs(system, stage_time, value);
52 },
53 [](const State& base, const State& increment, double scale) {
54 return add_scaled(base, increment, scale);
55 });
56 }
57};
58
59} // namespace oiseau::time
Classical fourth-order Runge-Kutta integrator.
Definition rk4.hpp:44