Skip to content

Instantly share code, notes, and snippets.

@lululombard
Created July 6, 2022 03:10
Show Gist options
  • Save lululombard/15edc5e8550893cda283a0c38cba9d56 to your computer and use it in GitHub Desktop.
Save lululombard/15edc5e8550893cda283a0c38cba9d56 to your computer and use it in GitHub Desktop.
Piecewise linear interpolation in C++
#include <iostream>
#include <map>
using namespace std;
float piecewise_linear_interpolate(map<float, float> value_mappings, float input);
int main() {
map<float, float> voltage_to_percent_mapping {
{ 09.5, 0.0 },
{ 10.8, 1.00 },
{ 12.8, 10.00 },
{ 12.9, 20.00 },
{ 13.0, 30.00 },
{ 13.1, 40.00 },
{ 13.2, 70.00 },
{ 13.3, 90.00 },
{ 13.4, 99.00 },
{ 13.5, 100.00 }
};
cout << piecewise_linear_interpolate(voltage_to_percent_mapping, 12.56) << endl;
return 0;
}
float piecewise_linear_interpolate(map<float, float> m, float input) {
// Out of bounds (too low)
if (input < m.begin()->first) {
return m.begin()->second;
}
// Out of bounds (too high)
if (input > m.rbegin()->first) {
return m.rbegin()->second;
}
// Find the two nearest values and interpolate between them
for (auto it = m.begin(); it != m.end(); ++it) {
if (input > it->first && input < next(it)->first) {
float x1 = it->first;
float y1 = it->second;
float x2 = next(it)->first;
float y2 = next(it)->second;
float slope = (y2 - y1) / (x2 - x1);
float y_intercept = y1 - (slope * x1);
return (slope * input) + y_intercept;
}
}
// Fallback (should never happen)
return 0.0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment