2021-08-01

Linear Interpolation

Given two points \(\textbf{p}\) and \(\textbf{q}\):

\[ \textbf{p} = (0,3), \quad \textbf{q} = (3,1) \]

Linear interpolation is about inserting new points along the line connecting the two points:

To do this, we have to give a value \(x\) in the interval \((x_1,x_2)\).

That is, between \(\textbf{p}\) and \(\textbf{q}\) in the horizontal axis:

\[ \begin{align} &\textbf{p} = (0,3), \quad \textbf{q} = (3,1)\\\\ &x_1 = 0, \quad y_1 = 3\\\\ &x_2 = 3, \quad y_2 = 1 \end{align} \]

For example, \(x = 1.5\):

To get the value \(y\) along the line, we use this equation:

\[ y = \frac{y_1 (x_2 - x) + y_2 (x - x_1)}{x_2 - x_1} \]

So we have:

\[ y = \frac{3 (3 - 1.5) + 1 (1.5 - 0)}{3 - 0} = 2 \]

JS code:

function linear_interpolation(p, q, x){
    var x1 = p[0],
        y1 = p[1],
        x2 = q[0],
        y2 = q[1];

    if(x < x1 || x > x2){
        throw 'value x must be between the x-coordinates of p and q';
    }

    var y = y1+((x-x1)*(y2-y1))/(x2-x1);

    return y;
}

Watch the video: