r/programming • u/mttd • Aug 11 '26
Moving integer division to floating-point is trivial
https://marc-b-reynolds.github.io/math/2026/08/10/IntDivByFP.html
112
Upvotes
r/programming • u/mttd • Aug 11 '26
View all comments
Show parent comment
27
u/taw Aug 11 '26
ELI5 version.
Computers are really fast at two things:
Now this trick isn't great in decimals, but we can sort of make it work.
If you want to calculate x/3, that's same as x*0.333333..., which is then the same as x * 333.333... / 1000.
So since we can multiply fast, do x * 334 (rounding that 333.333... up), getting a 6 digit number, then drop the last three digits, which is also super fast.
For this decimal example, it only works for every x=0 to 499, and for other divisors you also don't get perfect range.
But it works even better with binary 32bit x 32bit to 64bit.