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