Fast method to multiply integer by proper fraction without floats or overflow

后端 未结 3 1519
悲哀的现实
悲哀的现实 2021-02-19 12:56

My program frequently requires the following calculation to be performed:

Given:

  • N is a 32-bit integer
  • D is a 32-bit integer
  • abs(N) <=
3条回答
  •  闹比i
    闹比i (楼主)
    2021-02-19 13:31

    The basic correct approach to this is simply (uint64_t)x*n/d. That's optimal assuming d is variable and unpredictable. But if d is constant or changes infrequently, you can pre-generate constants such that exact division by d can be performed as a multiplication followed by a bitshift. A good description of the algorithm, which is roughly what GCC uses internally to transform division by a constant into multiplication, is here:

    http://ridiculousfish.com/blog/posts/labor-of-division-episode-iii.html

    I'm not sure how easy it is to make it work for a "64/32" division (i.e. dividing the result of (uint64_t)x*n), but you should be able to just break it up into high and low parts if nothing else.

    Note that these algorithms are also available as libdivide.

提交回复
热议问题