# C++ linear interpolation

An example of linear interpolation in C++.

```
typedef std::vector<double> DoubleVec;

int findNearestNeighbourIndex(const double ac_dfValue, DoubleVec x)
{
double lv_dfDistance = DBL_MAX;
int lv_nIndex = -1;

for (unsigned int i = 0; i < x.size(); i++) {
double newDist = ac_dfValue - x[i];
if (newDist >= 0 && newDist < lv_dfDistance) {
lv_dfDistance = newDist;
lv_nIndex = i;
}
}

return lv_nIndex;
}

DoubleVec interpolation(DoubleVec x, DoubleVec y,
DoubleVec xx)
{
double dx, dy;
DoubleVec slope, intercept, result;
slope.resize(x.size());
intercept.resize(x.size());
result.resize(xx.size());
int indiceEnVector;

for (unsigned i = 0; i < x.size(); i++) {
if (i < x.size() - 1) {
dx = x[i + 1] - x[i];
dy = y[i + 1] - y[i];
slope[i] = dy / dx;
intercept[i] = y[i] - x[i] * slope[i];
}
else {
slope[i] = slope[i - 1];
intercept[i] = intercept[i - 1];
}
}

for (unsigned i = 0; i < xx.size(); i++) {
indiceEnVector = findNearestNeighbourIndex(xx[i], x);
if (indiceEnVector != -1) {
result[i] = slope[indiceEnVector] *
xx[i] + intercept[indiceEnVector];
}
else
result[i] = DBL_MAX;
}
return result;
}

```

Returns the interpolated values for the XX grid(std::vector), using as reference the X (std::vector<double, argument variable>) – x axis and Y (std::vector<double, argument variable) – y axis.

How to test it:

```
int main()
{
DoubleVec x = { 1, 5, 10 };
DoubleVec y = { 10, 50, 100 };

DoubleVec xx;
for (unsigned i = 1; i < 10; ++i)
xx.push_back(i);

DoubleVec res = interpolation(x, y, xx);

return 0;
}

```

The result:

10 ; 20 ; 30 ; 40 ; 50 ; 60 ; 70 ; 80 ; 90 ; ### Author: Horațiu Condrea

My name is Horațiu Condrea, and I work as a Software Developer Manager at Siemens PLM Software. I hope that my experiments will prove to be useful for many of you guys/girls out there. Don’t forget to leave a comment whenever you run over a bug or something that is not working as it should be. For any kind of information contact me.

## One Reply to “C++ linear interpolation”

1. Sebastian says:

Even at the risk that I misunderstood something, but your function “findNearestNeighbourIndex” does not find the nearest value, but the nearest next smaller value. That’s perfectly fine for this particular case, but the name of the function is somewhat misleading for someone like me who came here via Google for a quick and dirty “findnearestneighbour” – template 🙂

Just sayin

This site uses Akismet to reduce spam. Learn how your comment data is processed.