Simvik

Linear interpolation

Interpolate between two calibration points without overflow. A medium embedded C problem (Fixed-point and signal processing), run and graded in the browser.

medium · Fixed-point and signal processing · interpolation · overflow

Calibration tables store a few points and interpolate between them. Given two points (x0, y0) and (x1, y1) with x0 < x1, return the value of y at x on the straight line through them: y0 + (x - x0) * (y1 - y0) / (x1 - x0), with the division truncating toward zero.

If x is outside the interval, clamp it: return y0 below x0 and y1 above x1. The intermediate product may not fit in 32 bits.

Starter code

int32_t lerp(int32_t x, int32_t x0, int32_t y0, int32_t x1, int32_t y1) {
  // Clamp x to [x0, x1], then interpolate.
  return y0;
}

Example tests

Halfway

printf("%d\n", lerp(5, 0, 0, 10, 100));

Expected output:

50

Offset interval

printf("%d\n", lerp(2, 0, 10, 4, 20));

Expected output:

15

Learn it first

More Fixed-point and signal processing problems