Advertisement
Guest User

Untitled

a guest
Mar 24th, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.08 KB | None | 0 0
  1. #include <map>
  2. #include <vector>
  3.  
  4. /**
  5. * Provides a basic interpolation mechanism in C++ using the STL.
  6. * Maybe not the fastest or most elegant method, but it works (for
  7. * linear interpolation!!), and is fast enough for a great deal of
  8. * purposes. It's also super easy to use, so that's a bonus.
  9. */
  10. class LinearInterpolator {
  11. public:
  12. LinearInterpolator() {}
  13.  
  14. /**
  15. * Adds a data point to the interpolator for future interpolation
  16. * @param x The anchor point where this data is located
  17. * @param d A vector containing multiple "y" values to be interpolated (columns)
  18. */
  19. void addDataPoint(double x, std::vector<double> &d) {
  20. // just add it to the map
  21. data[x] = d;
  22. }
  23.  
  24. /**
  25. * Interpolates our data sequence at a given point, for a given column of data
  26. * @param x The anchor point to interpolate at
  27. * @param column The column we want to interpolate on
  28. * @return y The interpolated value for this column
  29. */
  30. double interpolate(double x, unsigned int column) {
  31. // loop through all the keys in the map
  32. // to find one that is greater than our intended value
  33. std::map<double, std::vector<double> >::iterator it = data.begin();
  34. bool found = false;
  35. while(it != data.end() && !found) {
  36. if(it->first >= x) {
  37. found = true;
  38. break;
  39. }
  40.  
  41. // advance the iterator
  42. it++;
  43. }
  44.  
  45. // check to see if we're outside the data range
  46. if(it == data.begin()) {
  47. return data.begin()->second[column];
  48. }
  49. else if(it == data.end()) {
  50. // move the point back one, as end() points past the list
  51. it--;
  52. return it->second[column];
  53. }
  54. // check to see if we landed on a given point
  55. else if(it->first == x) {
  56. return it->second[column];
  57. }
  58.  
  59. // nope, we're in the range somewhere
  60. // collect some values
  61. double xb = it->first;
  62. double yb = it->second[column];
  63. it--;
  64. double xa = it->first;
  65. double ya = it->second[column];
  66.  
  67. // and calculate the result!
  68. // formula from Wikipedia
  69. return (ya + (yb - ya) * (x - xa) / (xb - xa));
  70. }
  71.  
  72. private:
  73. std::map<double, std::vector<double> > data;
  74. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement