A monte carlo pin cell spectral code for nuclear engineering applications.
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
interpolate.h
Go to the documentation of this file.
1 
9 #ifndef INTERPOLATE_H_
10 #define INTERPOLATE_H_
11 
12 #ifdef __cplusplus
13 #include <limits>
14 #include <math.h>
15 #include <stdlib.h>
16 #include <stdio.h>
17 #endif
18 
30 template <typename T, typename U>
31 int findUpperIndex(T* x, int upper_bound, int lower_bound, U pt) {
32 
33  /* Compute the delta between the two bounding indices */
34  int bound_delta = upper_bound - lower_bound;
35 
36  /* Compute the midpoint between the bounding indices */
37  int new_bound = floor(bound_delta / 2.0) + lower_bound;
38 
39  /* Check that bound are appropriate - if not, return infinity */
40  if (bound_delta <= 0)
41  return std::numeric_limits<int>::max();
42 
43  /* If the upper and lower bound only differ by one, we are are finished */
44  if (bound_delta == 1)
45  return upper_bound;
46 
47  /* If the pt is below the new bound, the new bound becomes upper bound */
48  else if (pt <= x[new_bound])
49  return findUpperIndex(x, new_bound, lower_bound, pt);
50 
51  /* If the pt is above the new bound, the new bound becomes lower bound */
52  else
53  return findUpperIndex(x, upper_bound, new_bound, pt);
54 }
55 
56 
68 template <typename T, typename U, typename P>
69 P linearInterp(T* x, T* y, int length, U pt) {
70 
71  int index = 0;
72  P y_pt = 0;
73 
74  /* If the length given is less than zero, exit program */
75  if (length <= 0)
76  exit(1);
77 
78  /* If the length is exactly 1 then return the only y value */
79  else if (length == 1)
80  y_pt = y[0];
81 
82  /* If the pt is less than all x values, return the y corresponding to
83  * the least x value */
84  else if (pt <= x[0])
85  y_pt = y[0];
86 
87  /* If the pt is greater than all x values, return the y corresponding to
88  * the greatest x value */
89  else if (pt >= x[length-1])
90  y_pt = y[length-1];
91 
92  /* Otherwise the pt is sandwiched between two of the x values */
93  else {
94  /* Find the index of x which bounds pt */
95  index = findUpperIndex(x, length-1, 0, pt);
96 
97  /* Find the slope of the line between the two sandwich points */
98  double m = (y[index] - y[index-1]) / (x[index] - x[index-1]);
99 
100  /* Return the interpolated point using the point-slope formula */
101  y_pt = m * (pt - x[index]) + y[index];
102  }
103 
104  return y_pt;
105 }
106 
107 
108 #endif /* INTERPOLATE_H_ */
int findUpperIndex(T *x, int upper_bound, int lower_bound, U pt)
This function finds the index of the first element in an array that is greater than the given paramet...
Definition: interpolate.h:31
P linearInterp(T *x, T *y, int length, U pt)
This function takes in the x and y values of a 1D function and returns the linearly interpolated y va...
Definition: interpolate.h:69