1

In a tight loop, I am doing a linear interpolation between two floating point values. However, the only necessary part of the result is the sign (whether the result is negative or positive). I'm doing a typical lerp operation right now, f way between a and b.

a + f * (b - a);

Is there something more efficient considering I just need to know the resulting sign and not the actual lerped value?

Edit: 'f' is a set of fixed distances along the interpolation, which are known beforehand.

user1043761
  • 696
  • 6
  • 22
  • 2
    As a general rule of thumb calculatations are faster than branches (e.g. `if`-statements). Your lerp code is optimal imho. – Jonas Byström Apr 11 '16 at 07:54
  • 1
    Is there one of the parameters a, b, f that is constant ? –  Apr 11 '16 at 13:34
  • As a Q&D hack, you can get the sign bit as the MSb in the IEEE representation. This spares a test. Anyway, unless the body of the if is really lightweight, any micro-optimization you can do here will go unnoticed. –  Apr 11 '16 at 13:44
  • @user1043761 Can you please mention the possible range of `f`? Your problem may be further simplified. – Minhas Kamal Apr 12 '16 at 03:35

1 Answers1

2

You can calculate whether interpolated value changes sign at given range:

if Sign(a) <> Sign(b) then  //don't forget about zero sign
  change occurs

In this case find f parameter, where lerp = 0

a + f0 * (b - a) = 0
f0 = a / (a+b)

For smaller values lerp has the same sign as a, for larger - the same sign as b, so you don't need to calculate lerp value - just compare f with f0

MBo
  • 77,366
  • 5
  • 53
  • 86
  • 1
    You are trading a multiply for a divide. This isn't a good idea. –  Apr 11 '16 at 13:33
  • @Yves Daoust I consider typical scenario of predetermined `a,b` and evaluation of lerp in some points. So root finding is one-time operation. Then any needed `f` will be compared with `f0` – MBo Apr 11 '16 at 15:13
  • As long as the OP hasn't said that `f` is constant, you cannot assume it. –  Apr 11 '16 at 15:14
  • @Yves Daoust Of course, `f` is not constant, but range ends are constants (I assume). – MBo Apr 11 '16 at 15:16
  • In my particular scenario, f will be a fixed set of points along the interpolation so this answer will be marked correct, as it did speed up my app. Respecifying in question – user1043761 Apr 11 '16 at 16:30