philsupertramp/game-math
Loading...
Searching...
No Matches
Integration.h
Go to the documentation of this file.
1#pragma once
2#include "../../Matrix.h"
3#include "../../sorting.h"
4#include "../utils.h"
5#include <functional>
6
7namespace integration {
60 std::pair<double, std::vector<double>> quad_adaptive_rec(
61 const std::function<double(double)>& fun,
62 const double& a,
63 const double& b,
64 const double& tol,
65 const double& hMin,
66 std::vector<double>& nodes,
67 Matrix<double>& values) {
68 double h = b - a;
69 if(h < hMin) {
70 // error
71 std::cerr << "H too small! h = " << h << std::endl;
72 exit(-1);
73 }
74
75 Matrix<double> x = { { a }, { a + (h / 2.0) }, { b } };
76 if(values.rows() == 0) {
77 values = x.Apply(fun);
78 } else if(values.rows() < 3) {
79 values = { { values(0, 0) }, { fun(x(1, 0)) }, { values(1, 0) } };
80 }
81
82 auto qSimpson = (h / 6.0) * (values(2, 0) + 4.0 * values(1, 0) + values(0, 0));
83 auto qTrapez = (h / 2.0) * (values(2, 0) + values(0, 0));
84
85 auto error = fabs(qSimpson - qTrapez);
86
87 nodes.push_back(x(1, 0));
88
89 if(error <= tol) { return { qSimpson, nodes }; }
90
91 auto hTol = tol / 2.0;
92 auto leftValues = values.GetSlice(0, 1, 0, 0);
93 auto resLeft = quad_adaptive_rec(fun, a, x(1, 0), hTol, hMin, nodes, leftValues);
94 auto rightValues = values.GetSlice(1, 2, 0, 0);
95 auto resRight = quad_adaptive_rec(fun, x(1, 0), b, hTol, hMin, nodes, rightValues);
96
97 return { resLeft.first + resRight.first, nodes };
98 }
99} // namespace integration
100
117std::pair<double, std::vector<double>> quadrature(
118const std::function<double(double)>& fun,
119const double& lower,
120const double& upper,
121const double& tol,
122const double& hMin) {
123 std::vector<double> nodes = { lower, upper };
125 auto res = integration::quad_adaptive_rec(fun, lower, upper, tol, hMin, nodes, q);
126 res.second = sort(res.second);
127 return res;
128}
std::pair< double, std::vector< double > > quadrature(const std::function< double(double)> &fun, const double &lower, const double &upper, const double &tol, const double &hMin)
Definition: Integration.h:117
Definition: Matrix.h:42
size_t rows() const
Definition: Matrix.h:193
Matrix GetSlice(size_t rowStart) const
Definition: Matrix.h:609
Matrix< T > Apply(const std::function< T(T)> &fun) const
Definition: Matrix.h:375
Definition: Integration.h:7
std::pair< double, std::vector< double > > quad_adaptive_rec(const std::function< double(double)> &fun, const double &a, const double &b, const double &tol, const double &hMin, std::vector< double > &nodes, Matrix< double > &values)
Definition: Integration.h:60
std::vector< T > sort(const std::vector< T > &in)
Definition: sorting.h:33