Piecewise linear interpolation

1k Views Asked by At

A really simple question - how does it work? Linear interpolation is quite easy and understandable:

for (i = 0; i < N; i++)
{
    X = ((A * i) + (B * (N - i))) / N;
} 

But how does it work with more than two point? I want to make it as smooth as possible.

EDIT:

I suppose i didn't describe the situation enough, or i just don't fully understand. I need to figure this out, so that i can get n numbers between each of 2..k nodes. At start I just interpolated between each pair, but the result wasn't fluid enough to use with animation.

1

There are 1 best solutions below

0
On

Suppose you have a sequence of $x$-coordinates $x_1 < x_2 < \ldots < x_n$ and corresponding $y$ values $y_1, \ldots, y_n$.

Then, if you are given a value $x$, here's how you calculate the corresponding $y$ by using piecewise linear interpolation:

(1) First, you find out which interval your given $x$ lies in. In other words, you find an index $i$ such that $x_i \le x \le x_{i+1}$.

(2) Then you just do linear interpolation on this interval. So, the desired $y$ value is just $$ y = \frac{x_{i+1} - x}{x_{i+1} - x_i}y_i + \frac{x - x_i}{x_{i+1} - x_i}y_{i+1} $$ The curve you get will be a sequence of straight lines with joints at the points $(x_i, y_i)$, so it won't be smooth. If you want a smooth curve, you have to use something more complicated than piecewise linear interpolation. Spline interpolation is one option.