NumCpp  2.18.0
A Templatized Header Only C++ Implementation of the Python NumPy Library
Loading...
Searching...
No Matches
romberg.hpp
Go to the documentation of this file.
1
32#pragma once
33
34#include <functional>
35
36#include "NumCpp/Core/Types.hpp"
38#include "NumCpp/NdArray.hpp"
40
41namespace nc::integrate
42{
43 //============================================================================
44 // Method Description:
54 inline double romberg(const double low, const double high, const uint8 n, const std::function<double(double)>& f)
55 {
56 NdArray<double> rombergIntegral(n);
57
58 // R(0,0) Start with trapezoidal integration with N = 1
59 rombergIntegral(0, 0) = trapazoidal(low, high, 1, f);
60
61 double h = high - low;
62 for (uint8 step = 1; step < n; step++)
63 {
64 h *= 0.5;
65
66 // R(step, 0) Improve trapezoidal integration with decreasing h
67 double trapezoidal_integration = 0.;
68 const uint32 stepEnd = utils::power(2, step - 1);
69 for (uint32 tzStep = 1; tzStep <= stepEnd; ++tzStep)
70 {
71 const double deltaX = (2. * static_cast<double>(tzStep - 1)) * h;
72 trapezoidal_integration += f(low + deltaX);
73 }
74
75 rombergIntegral(step, 0) = 0.5 * rombergIntegral(step - 1, 0);
76 rombergIntegral(step, 0) += trapezoidal_integration * h;
77
78 // R(m,n) Romberg integration with R(m,1) -> Simpson rule, R(m,2) -> Boole's rule
79 for (uint8 rbStep = 1; rbStep <= step; ++rbStep)
80 {
81 const double k = utils::power(4, rbStep);
82 rombergIntegral(step, rbStep) = k * rombergIntegral(step, rbStep - 1);
83 rombergIntegral(step, rbStep) -= rombergIntegral(step - 1, rbStep - 1);
84 rombergIntegral(step, rbStep) /= (k - 1.);
85 }
86 }
87
88 return rombergIntegral.back();
89 }
90} // namespace nc::integrate
Holds 1D and 2D arrays, the main work horse of the NumCpp library.
Definition NdArrayCore.hpp:135
const_reference back() const noexcept
Definition NdArrayCore.hpp:2359
Definition gauss_legendre.hpp:43
double romberg(const double low, const double high, const uint8 n, const std::function< double(double)> &f)
Definition romberg.hpp:54
double trapazoidal(const double low, const double high, const uint32 n, const std::function< double(double)> &f) noexcept
Definition trapazoidal.hpp:51
dtype power(dtype inValue, uint8 inPower) noexcept
Definition Utils/power.hpp:44
std::uint8_t uint8
Definition Types.hpp:42
std::uint32_t uint32
Definition Types.hpp:40