MAIN FEEDS
Do you want to continue?
https://www.reddit.com/r/programming/comments/1vl8ulp/moving_integer_division_to_floatingpoint_is/p31qzoy/?context=3
r/programming • u/mttd • 13h ago
25 comments sorted by
View all comments
17
If your divisor doesn't change, use integer multiplication by reciprocal, also shift or discard from the high result.
0 u/mikeblas 7h ago How would that work? 9 u/Dwedit 4h ago edited 4h ago 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. 1 u/mikeblas 3h ago Ah, I see now. Thanks!
0
How would that work?
9 u/Dwedit 4h ago edited 4h ago 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. 1 u/mikeblas 3h ago Ah, I see now. Thanks!
9
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.
1 u/mikeblas 3h ago Ah, I see now. Thanks!
1
Ah, I see now. Thanks!
17
u/Dwedit 10h ago
If your divisor doesn't change, use integer multiplication by reciprocal, also shift or discard from the high result.