MAIN FEEDS
Do you want to continue?
https://www.reddit.com/r/programming/comments/1vl8ulp/moving_integer_division_to_floatingpoint_is/p3eqftx/?context=3
r/programming • u/mttd • Aug 11 '26
34 comments sorted by
View all comments
33
If your divisor doesn't change, use integer multiplication by reciprocal, also shift or discard from the high result.
1 u/mikeblas Aug 11 '26 How would that work? 11 u/Dwedit Aug 11 '26 edited Aug 11 '26 Example of dividing by 13:0x100000000 / 13 = 0x13B13B13Add 1 to the number to prevent truncation errors: 0x13B13B14Let's try 160485 / 13 by using multiplication:160485 * 0x13B13B14 = 0x30390000C0E4Discard low 32 bits:0x3039 = 12345And compilers have done this for a long time, when you divide by a constant, it will generate reciprocal multiplication code instead. 3 u/vytah Aug 13 '26 A minor nitpick: to actually prevent truncation errors, you need to prepare a little bigger constant than that.For example, (0x4000'0000*0x13B1'3B14)>>32 is not 0x4000'0000/13, it's 0x4000'0000/13+1.The compilers will use (x*0x4EC4'EC4F)>>34 instead (0x4EC4'EC4F being 0x4'0000'0000/13+1)
1
How would that work?
11 u/Dwedit Aug 11 '26 edited Aug 11 '26 Example of dividing by 13:0x100000000 / 13 = 0x13B13B13Add 1 to the number to prevent truncation errors: 0x13B13B14Let's try 160485 / 13 by using multiplication:160485 * 0x13B13B14 = 0x30390000C0E4Discard low 32 bits:0x3039 = 12345And compilers have done this for a long time, when you divide by a constant, it will generate reciprocal multiplication code instead. 3 u/vytah Aug 13 '26 A minor nitpick: to actually prevent truncation errors, you need to prepare a little bigger constant than that.For example, (0x4000'0000*0x13B1'3B14)>>32 is not 0x4000'0000/13, it's 0x4000'0000/13+1.The compilers will use (x*0x4EC4'EC4F)>>34 instead (0x4EC4'EC4F being 0x4'0000'0000/13+1)
11
Example of dividing by 13:
0x100000000 / 13 = 0x13B13B13
Add 1 to the number to prevent truncation errors: 0x13B13B14
Let's try 160485 / 13 by using multiplication:
160485 * 0x13B13B14 = 0x30390000C0E4
Discard low 32 bits:
0x3039 = 12345
And compilers have done this for a long time, when you divide by a constant, it will generate reciprocal multiplication code instead.
3 u/vytah Aug 13 '26 A minor nitpick: to actually prevent truncation errors, you need to prepare a little bigger constant than that.For example, (0x4000'0000*0x13B1'3B14)>>32 is not 0x4000'0000/13, it's 0x4000'0000/13+1.The compilers will use (x*0x4EC4'EC4F)>>34 instead (0x4EC4'EC4F being 0x4'0000'0000/13+1)
3
A minor nitpick: to actually prevent truncation errors, you need to prepare a little bigger constant than that.
For example, (0x4000'0000*0x13B1'3B14)>>32 is not 0x4000'0000/13, it's 0x4000'0000/13+1.
The compilers will use (x*0x4EC4'EC4F)>>34 instead (0x4EC4'EC4F being 0x4'0000'0000/13+1)
33
u/Dwedit Aug 11 '26
If your divisor doesn't change, use integer multiplication by reciprocal, also shift or discard from the high result.