To do a linear interpolation between two variables a
and b
given a fraction f
, I'm currently using this code:
float lerp(float a, float b, float f)
{
return (a * (1.0 - f)) + (b * f);
}
I think there's probably a more efficient way of doing it. I'm using a microcontroller without an FPU, so floating point operations are done in software. They are reasonably fast, but it's still something like 100 cycles to add or multiply.
Any suggestions?
n.b. for the sake of clarity in the equation in the code above, we can omit specifying 1.0
as an explicit floating-point literal.
Disregarding differences in precision, that expression is equivalent to
float lerp(float a, float b, float f)
{
return a + f * (b - a);
}
That's 2 additions/subtractions and 1 multiplication instead of 2 addition/subtractions and 2 multiplications.