7 ms·
Not being snarky, at the simplest level by knowing x ahead of time you can change your code from y = n/2 into y = n * 0.5. Not wildly important by itself, but i
by codefreakxff 3y ago
Not being snarky, at the simplest level by knowing x ahead of time you can change your code from y = n/2 into y = n * 0.5. Not wildly important by itself, but in a loop - maybe… I suspect compilers optimize for that already.
- shmerl 3y agoI still don't get it. How do you know that 1/x = 0.abc... without performing the division? I mean in general case, not in something matching binary tricks. Such as 1/3 for example. Unless you mean you somehow know the value of 1/x ahead of time. But where does it come from?
- pdonis 3y agoIf you know the divisor x ahead of time you can pre-compute 1/x at compile time, so that your actual compiled code never does the division--only your compiler does. Your actual compiled code just does the multiplication by a pre-computed constant (and the compiled code doesn't have to know that that constant was pre-computed as the reciprocal of x).
- shmerl 3y agoAh, thanks for clarifying.
- deleted 3y ago[deleted]
- a_e_k 3y agoOften, you can amortize a division or reciprocal by calculating it once and then reusing it. Frequently the divisor is dynamic, but reused locally. For example, if you want to normalize a 3D vector you could do: mag = sqrt(x*x + y*y + z*z) x /= mag y /= mag z /= mag That's three divisions with the same divisor. But you could instead do: invMag = 1.0 / sqrt(x*x + y*y + z*z) x *= invMag y *= invMag z *= invMag There's still a single division (or reciprocal) done here. But you've eliminated at least the other two. (And it's even better if you have an rsqrt function.)
- fuzzylightbulb 3y agoso basically just precompute all the answers you will need and then just look up the values later?
- circuit10 3y agoThere’s no lookup needed if the value is constant