## Piecewise Linear Interpolation

Let's turn back to our half-a-circle example. This time, we'll limit ourselves to a quarter of a circle, that is, positive values of x and y. We start by calculating the y values for x equal to 0, 0.2, . . . , 1. We'll store the results in vectors xp and yp:

>>> xp array([ 0. , 0.2, 0.4, 0.6, 0.8, 1. ]) >>> yp = sqrt(l-xp**2)

We'd like to calculate the values of y for x values equal to 0.1, 0.3, . . . , 0.9 given xp and yp. We'll use the function interp(x, xp, yp) for this. The function returns the value of the piecewise linear function defined by xp, yp at a requested point x. What this means is interpQ returns the value of a point on a line connecting two adjacent (xp, yp) points:

>>> xi = arange(0.1, 1.0, 0.2) >>> yi = interp(xi, xp, yp)

The vector yi holds the interpolated values at points 0.1, 0.3, . . ., 0.9.

The following visualizes a piecewise linear interpolation for the quarter of a circle:

>>> plot(xp, yp, 'or', label='interpolation points')

>>> plot(xp, yp, '--r', label='piecewise linear function')

>>> plot(xi, yi, 'sg', label='interpolated values')

>>> title('Piecewise linear interpolation')

Figure 8-3 shows the results of this visualization.

Piecewise linear interpolation Figure 8-3. Piecewise linear interpolation

Figure 8-3. Piecewise linear interpolation

For the purpose of the example, the values xp and yp are computed, but in reality, these values can originate from sampled data. As you can see from the graph, the interpolated value at 0.9 is considerably less accurate than other interpolated values. Typically, the more points you add, the more accurate the result.