philsupertramp/game-math
Loading...
Searching...
No Matches
ode45.h
Go to the documentation of this file.
1
20#pragma once
21
22#include "../utils.h"
23#include "ode.h"
24#include <functional>
25#include <vector>
26
35ODEResult ODE45(const ODE& fun, const std::vector<double>& tInterval, const Matrix<double>& y0, double h = 0.0) {
36 size_t dim = tInterval.size();
37 size_t elem_size = y0.columns();
38 if(h == 0) { h = (tInterval[dim - 1] - tInterval[0]) / 1000; }
39 auto result_dim = int((tInterval[dim - 1] - tInterval[0]) / h) + 1;
40
41 Matrix<double> t(0, result_dim, 1, 1);
42 size_t n = result_dim;
43 Matrix<double> y = zeros(n, elem_size);
44
45 Matrix<double> a({ { 0, 0, 0, 0, 0, 0, 0 },
46 { 1.0 / 5.0, 0, 0, 0, 0, 0, 0 },
47 { 3.0 / 40.0, 9.0 / 40.0, 0, 0, 0, 0, 0 },
48 { 44.0 / 45.0, -56.0 / 15.0, 32.0 / 9.0, 0, 0, 0, 0 },
49 { 19372.0 / 6561.0, -25360.0 / 2187.0, 64448.0 / 6561.0, -212.0 / 729.0, 0, 0, 0 },
50 { 9017.0 / 3168.0, -355.0 / 33.0, 46732.0 / 5247.0, 49.0 / 176.0, -5103.0 / 18656.0, 0, 0 },
51 { 35.0 / 384.0, 0, 500.0 / 1113.0, 125.0 / 192.0, -2187.0 / 6784.0, 11.0 / 84.0, 0 } });
52
53 Matrix<double> c({ { 0, 1.0 / 5.0, 3.0 / 10.0, 4.0 / 5.0, 8.0 / 9.0, 1.0, 1.0 } });
54
55 Matrix<double> b5({ { 35.0 / 384.0, 0, 500.0 / 1113.0, 125.0 / 192.0, -2187.0 / 6784.0, 11.0 / 84.0 } });
56 [[maybe_unused]] Matrix<double> b4(
57 { { 5179.0 / 57600.0, 0, 7571.0 / 16695.0, 393.0 / 640.0, -92097.0 / 339200.0, 187.0 / 2100.0, 1.0 / 40.0 } });
58
59
60 y.SetRow(0, y0);
61 t(0, 0) = tInterval[0];
62 for(size_t l = 0; l < n - 1; l++) {
63 t(l + 1, 0) = t(l, 0) + h;
64 auto k = zeros(6, elem_size);
65 for(size_t i_k = 0; i_k < 6; i_k++) {
66 Matrix<double> y_k = y(l);
67
68 for(size_t j = 0; j < i_k; j++) {
69 for(size_t elem = 0; elem < elem_size; elem++) { y_k(0, elem) += h * a(i_k, j) * k(j, elem); }
70 }
71 k.SetRow(i_k, fun(t(l, 0) + c(0, i_k) * h, y_k));
72 }
73 auto y_l = y(l) + (b5 * k) * h;
74 y.SetRow(l + 1, y_l);
75 }
76 return { y, t };
77}
Definition: Matrix.h:42
void SetRow(size_t index, const Matrix< T > &other)
Definition: Matrix.h:541
size_t columns() const
Definition: Matrix.h:198
Matrix< double > zeros(size_t rows, size_t columns, size_t elements=1)
ODEResult ODE45(const ODE &fun, const std::vector< double > &tInterval, const Matrix< double > &y0, double h=0.0)
Definition: ode45.h:35
std::function< Matrix< double >(double, Matrix< double >)> ODE
alias for ODE
Definition: ode.h:17
Definition: ode.h:25