CoolProp 8.0.0
An open-source fluid property and humid air property database
finite_diff.h
Go to the documentation of this file.
1#ifndef FINITE_DIFF_H
2#define FINITE_DIFF_H
3
4#include <Eigen/Dense>
5
6template <typename Callable>
7auto romberg_diff(Callable& func, double x, std::size_t order = 2, double h = 0.1) {
8
9 // Initialize the table. This is a 2D (order x order) Richardson table:
10 // the loops below index r(j, i) with both i and j running up to order-1,
11 // so it must be a fully-dynamic 2D array (ArrayXXd), not the Dynamic x 1
12 // column-vector ArrayXd (which asserts/UB for any order > 1).
13 auto r = Eigen::ArrayXXd(order, order);
14
15 // Compute the first column using the central difference formula
16 for (auto i = 0; i < order; ++i) {
17 r(i, 0) = (func(x + h) - func(x - h)) / (2 * h);
18 h /= 2.0;
19 }
20
21 // Apply Richardson extrapolation
22 for (auto i = 1; i < order; ++i) {
23 for (auto j = i; j < order; ++j) {
24 double fouri = pow(4, i);
25 r(j, i) = (fouri * r(j, i - 1) - r(j - 1, i - 1)) / (fouri - 1);
26 }
27 }
28
29 return r(order - 1, order - 1);
30}
31
32#endif // FINITE_DIFF_H