PolynomialInterpolation.h
Go to the documentation of this file.
1 #ifndef _utl_PolynomialInterpolation_h_
2 #define _utl_PolynomialInterpolation_h_
3 
4 #include <cmath>
5 #include <utl/ErrorLogger.h>
6 
7 
8 namespace utl {
9 
31  inline
32  double
33  PolynomialInterpolation(const unsigned int n, const double px[], const double py[],
34  const double x, double& dy)
35  {
36  if (!n)
37  return 0;
38 
39  double minDist = std::fabs(x - px[0]);
40  unsigned int k = 0;
41  double c[n];
42  double d[n];
43  c[0] = py[0];
44  d[0] = py[0];
45  double oldx = px[0];
46  for (unsigned int i = 1; i < n; ++i) {
47  const double newx = px[i];
48  if (oldx == newx) {
49  ERROR("x values should be distinct.");
50  return 0;
51  }
52  oldx = newx;
53  const double dist = std::fabs(x - newx);
54  if (dist < minDist) {
55  minDist = dist;
56  k = i;
57  }
58  c[i] = d[i] = py[i];
59  }
60 
61  double y = py[k];
62 
63  for (unsigned int m = 1; m < n; ++m) {
64  const unsigned int nm = n - m;
65  for (unsigned int i = 0; i < nm; ++i) {
66  const double xa = px[i];
67  const double xb = px[i+m];
68  const double dx = xb - xa;
69  const double cd = (c[i+1] - d[i]) / dx;
70  c[i] = (x-xa)*cd;
71  d[i] = (x-xb)*cd;
72  }
73  dy = (2*k < nm) ? c[k] : d[--k];
74  y += dy;
75  }
76 
77  return y;
78  }
79 
80 
93  inline
94  double
95  PolynomialInterpolation(const unsigned int n, const double px[], const double py[],
96  const double x)
97  {
98  double dummy;
99  return PolynomialInterpolation(n, px, py, x, dummy);
100  }
101 
102 }
103 
104 #endif
double PolynomialInterpolation(const unsigned int n, const double px[], const double py[], const double x, double &dy)
Perform polynomial interpolation or extrapolation.
#define ERROR(message)
Macro for logging error messages.
Definition: ErrorLogger.h:165
constexpr double m
Definition: AugerUnits.h:121

, generated on Tue Sep 26 2023.