Question

I tried this over Python. I am aware that using ints and doing their division will only return the integer value of quotient, truncating the decimal part. On this note:

3 / 2 = 1

Sounds perfectly all right... However when the dividend is negative, then it's mind boggling for me to understand what's happening behind the scenes ??

-3 / 2 = -2

Here's the output:

enter image description here

Was it helpful?

Solution

The integer division there is just taking the floor of the number obtained at the end.

3/2  -> floor(1.5)  ->  1
-3/2 -> floor(-1.5) -> -2

OTHER TIPS

The float value is not truncated - it is rounded down, i.e towards negative infinity.

Natural numbers and real numbers both have the property that (n+d)/d equals (n/d)+1. Real numbers have the additional property that (-n)/d equals -(n/d). It is possible to define integers to have either of the above properties, but not both.

Although the first property is often the more useful of the two, the easiest way to implement integer division with a negative dividend, in both hardware and software, is to invert the sign of the dividend and then invert the sign of the result. Early languages performed integer division in this way because it was easy; the fact that many programs were written to expect this behavior, many languages continued in the tradition.

Arguably, the best thing for a language to do would be to use "word" operators (e.g. divt) for division rather than punctuation. That would allow code to specify whether it wants a truncated division or a floored division, is willing to let the compiler arbitrarily pick whichever would be fastest in any given scenario, or is willing to have the compiler do anything with negative numbers in exchange for making positive numbers work faster (e.g. on a CPU with an "unsigned divide" instruction which is faster than "signed divide", such an operator would allow the CPU to use the "unsigned" one). I don't know any current languages that do that, though.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top