2

Is there an elegant way to do linear interpolation using integers? (To average ADC measurements in microcontroller, ADC measurements are 12bit, microcontroller works fine with 32bit integers). Coefficient f is in [0, 1] range.

float lerp(float a, float b, float f)
{
    return a + f * (b - a);
}
DikobrAz
  • 3,557
  • 4
  • 35
  • 53

1 Answers1

5

Well, since you have so many extra integer bits to spare, a solution using ints would be:

Use an integer for your parameter F, with F from 0 to 1024 instead of a float from 0 to 1. Then you can just do:

(A*(1024-F) + B * F) >> 10

without risk of overflow.

In fact, if you need more resolution in your parameter, you can pick the maximum value of F as any power of 2 up to 2**19 (if you are using unsigned ints; 2**18 otherwise).

This doesn't do a good job of rounding (it truncates instead) but it only uses integer operations, and avoids division by using the shift operator. It still requires integer multiplication, which a number of MCUs don't have hardware for, but hopefully it won't be too bad.

Gretchen
  • 2,274
  • 17
  • 16