philsupertramp/game-math
Loading...
Searching...
No Matches
odeTrapez.h
Go to the documentation of this file.
1
12#pragma once
13
14#include "../lin_alg/newton.h"
15#include "../utils.h"
16#include "ode.h"
17#include <iostream>
18
28ODETrapez(const ODE& fun, const std::vector<double>& tInterval, const Matrix<double>& y0, const ODEOption& option) {
29 size_t dim = tInterval.size();
30 size_t elem_size = y0.columns();
31 auto h = option.h;
32 auto TOL = option.TOL;
33 auto maxIter = option.maxIter;
34 auto Jac = option.Jac;
35 if(h == 0) { h = (tInterval[dim - 1] - tInterval[0]) / 1000.0; }
36 int n = int((tInterval[dim - 1] - tInterval[0]) / h) + 1;
37
38 auto t = Matrix<double>(0, n, 1, 1);
39 auto iter = Matrix<int>(0, n, 1);
40 auto y = zeros(n, elem_size);
41
42 t(0, 0) = tInterval[0];
43 y.SetRow(0, y0);
44 auto E = eye(elem_size);
45
46 for(int i = 1; i < n; ++i) {
47 auto y_act = y(i - 1).Transpose();
48 t(i, 0) = t(i - 1, 0) + h;
49 int k = 0;
50 auto delta = ones(elem_size);
51 auto prev_fun = fun(t(i - 1, 0), y_act);
52
53 while(norm(delta) > TOL && k < maxIter) {
54 auto current_fun = fun(t(i, 0), y_act);
55 auto F = -1.0 * (y(i - 1).Transpose() + h / 2 * (prev_fun + current_fun) - y_act);
56 auto J = h / 2 * Jac(t(i, 0), y_act) - E;
57
58 delta = gaussSeidel(J, F);
59 y_act += delta;
60 k++;
61 }
62 if(k == maxIter) {
63 // err max iteration reached, did not convert.
64 }
65 iter(i, 0) = k;
66 y.SetRow(i, y_act);
67 }
68 return { y, t, iter };
69}
70
Definition: Matrix.h:42
size_t columns() const
Definition: Matrix.h:198
Matrix< double > gaussSeidel(const Matrix< double > &A, const Matrix< double > &b)
Definition: gaussSeidel.h:29
Matrix< double > eye(size_t rows, size_t columns=0)
double norm(const Matrix< double > &in)
Matrix< double > ones(size_t rows, size_t columns=1, size_t elements=1)
Matrix< double > zeros(size_t rows, size_t columns, size_t elements=1)
ODEResult ODETrapez(const ODE &fun, const std::vector< double > &tInterval, const Matrix< double > &y0, const ODEOption &option)
Definition: odeTrapez.h:28
std::function< Matrix< double >(double, Matrix< double >)> ODE
alias for ODE
Definition: ode.h:17
Definition: ode.h:56
double TOL
tolerance for the algorithm to determine convergence
Definition: ode.h:60
int maxIter
max iterations for integrated newton steps
Definition: ode.h:62
double h
step width of t
Definition: ode.h:58
ODEJac Jac
jacobian matrix of given function
Definition: ode.h:64
Definition: ode.h:25