tech-kern archive

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]

A Fast Alternative to Modulo Reduction



Hi,

I came across an interesting article [1] which talks about a faster
alternative to the mod operation (x % N) for mapping a number to a
fixed range, such as [0, N), which is common when we want to generate
random numbers within a given range, or map a hash value to a range of
indices in an array.

It says divisions are more expensive as compared to multiplications,
so instead of doing x % N, we can use (x * N) >> 32. Both operations
are not _equivalent_ but he proves that the latter is also a fair
mapping of x in the range [0, N) for 32 bit integers.

Is this result useful? For example I saw that rand(3) uses the %
operation to map the value in the range of RAND_MAX.

[1]: http://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/

-
Abhinav


Home | Main Index | Thread Index | Old Index