>It's worth noting that you can generally divide much faster if you know the divisor ahead of time
Division is just multiplication with 1/x so i don't understand
>It's worth noting that you can generally divide much faster if you know the divisor ahead of time
Division is just multiplication with 1/x so i don't understand
It gets tricky because 2^32/3 is not an integer, so you must round it. This introduces error; the idea is to show that the error is wiped out by the flooring divide. I did the monster math here:
https://ridiculousfish.com/blog/posts/labor-of-division-epis...
Also, with integers, a signed right shift is rounding down (towards negative infinity), whereas the division operator/instruction in many languages/hardware is rounding towards 0.
To adjust the rounding, you'd add the sign-bit to the first fractional bit before shifting the last step. Let's say that 'x' is a signed long, and a signed long has 64 bits, then:
result = ((x >> amount-1) + ((unsigned long)x >> 63)) >> 1;
Yes, but this was historically okay on an x87 FPU which had more precise representation than the common external formats.
Here's an example: https://godbolt.org/z/8vG637fb5
It compiles x/6 to some mad multiplication, bitshift and add.
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.)