Ant
Ant

Reputation: 1708

Compiler optimal division for float

I am writing a function to affect the feel of a control and found that dividing by 15.9 was about right. My natural instinct is to change this to a divide by 16 because that can be optimised by the compiler to a shift operation. In this case however the value is a float. Are there optimal divisors in float division?

Upvotes: 2

Views: 150

Answers (2)

Henrik
Henrik

Reputation: 23324

Dividing a float by 16 is pretty easy too. You just have to decrement the exponent by 4. But I don't think the compiler does any optimization here, because then it would also have to check for underflow.

To be clear: I'm not proposing to directly manipulate the exponent bits. I just wanted to indicate that the potentially fastest divisors for float are also the powers of two.

Upvotes: 0

Damon
Damon

Reputation: 70186

Why not multiply by 0.0628930818 instead? If dividing by 15.9 is "about right", then multiplying by the reciprocal although possibly not perfectly accurate to the last decimal will still be "about right". An optimizing compiler might possibly even do this automatically, if some "permissive math" flags are used (normally, this is strictly not allowable, since it may lose some precision).

It's more accurate than dividing by 16, anyway. And, it's not as much of a hack as tampering with the exponent bits.

Upvotes: 2

Related Questions