Floor division with negative number

The // operator explicitly floors the result. Quoting the Binary arithmetic operations documentation: the result is that of mathematical division with the ‘floor’ function applied to the result. Flooring is not the same thing as rounding to 0; flooring always moves to the lower integer value. See the math.floor() function: Return the floor of x, … Read more

Fast multiplication/division by 2 for floats and doubles (C/C++)

This is one of those highly-application specific things. It may help in some cases and not in others. (In the vast majority of cases, a straight-forward multiplication is still best.) The “intuitive” way of doing this is just to extract the bits into a 64-bit integer and add the shift value directly into the exponent. … Read more

Why is division more expensive than multiplication?

CPU’s ALU (Arithmetic-Logic Unit) executes algorithms, though they are implemented in hardware. Classic multiplications algorithms includes Wallace tree and Dadda tree. More information is available here. More sophisticated techniques are available in newer processors. Generally, processors strive to parallelize bit-pairs operations in order the minimize the clock cycles required. Multiplication algorithms can be parallelized quite … Read more

What is the purpose of the div() library function?

From the C99 Rationale document: (7.20.6.2 The div, ldiv, and lldiv functions) Because C89 had implementation-defined semantics for division of signed integers when negative operands were involved, div and ldiv, and lldiv in C99, were invented to provide well-specified semantics for signed integer division and remainder operations. The semantics were adopted to be the same … Read more