What is the behavior of integer division?

463,230

Solution 1

Will result always be the floor of the division? What is the defined behavior?

Not quite. It rounds toward 0, rather than flooring.

6.5.5 Multiplicative operators

6 When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded.88) If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.

and the corresponding footnote:

  1. This is often called ‘‘truncation toward zero’’.

Of course two points to note are:

3 The usual arithmetic conversions are performed on the operands.

and:

5 The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined.

[Note: Emphasis mine]

Solution 2

Dirkgently gives an excellent description of integer division in C99, but you should also know that in C89 integer division with a negative operand has an implementation-defined direction.

From the ANSI C draft (3.3.5):

If either operand is negative, whether the result of the / operator is the largest integer less than the algebraic quotient or the smallest integer greater than the algebraic quotient is implementation-defined, as is the sign of the result of the % operator. If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.

So watch out with negative numbers when you are stuck with a C89 compiler.

It's a fun fact that C99 chose truncation towards zero because that was how FORTRAN did it. See this message on comp.std.c.

Solution 3

Yes, the result is always truncated towards zero. It will round towards the smallest absolute value.

-5 / 2 = -2
 5 / 2 =  2

For unsigned and non-negative signed values, this is the same as floor (rounding towards -Infinity).

Solution 4

Where the result is negative, C truncates towards 0 rather than flooring - I learnt this reading about why Python integer division always floors here: Why Python's Integer Division Floors

Solution 5

Will result always be the floor of the division?

No. The result varies, but variation happens only for negative values.

What is the defined behavior?

To make it clear floor rounds towards negative infinity,while integer division rounds towards zero (truncates)

For positive values they are the same

int integerDivisionResultPositive= 125/100;//= 1
double flooringResultPositive= floor(125.0/100.0);//=1.0

For negative value this is different

int integerDivisionResultNegative= -125/100;//=-1
double flooringResultNegative= floor(-125.0/100.0);//=-2.0
Share:
463,230

Related videos on Youtube

T.T.T.
Author by

T.T.T.

Updated on May 28, 2021

Comments

  • T.T.T.
    T.T.T. almost 3 years

    For example,

    int result;
    
    result = 125/100;
    

    or

    result = 43/100;
    

    Will result always be the floor of the division? What is the defined behavior?

    • Peter Cordes
      Peter Cordes over 6 years
      Summary: signed integer division truncates towards zero. For non-negative results, this is the same as floor (round towards -Infinity). (Beware that C89 doesn't guarantee this, see answers.)
    • Timothy L.J. Stewart
      Timothy L.J. Stewart over 5 years
      Everyone keeps saying "truncate toward zero" or "ceiling" or "floor" like the code is making a deliberate decision on which technique to use. If the code could talk it would say "I just throw the dam fraction part in the trash and move on with life"
    • 13steinj
      13steinj over 5 years
      @TimothyL.J.Stewart The "code" is making a deliberate decision. As per the specification, integer division is meant to be T(runcation)-division. Because of this, the modulo/remainder operator is implented differently than if it were in another language, say, Python or Ruby. See this for a list of different ways languages do the modulo operator and this paper that lists out at least five of the common ways programming languages decide to do div/modulo.
    • Timothy L.J. Stewart
      Timothy L.J. Stewart over 5 years
      @13steinj I'm speaking colloquially per the comments it was turning into a "it's truncate toward zero... no it's floor... no if its negative its ceiling..." sometimes technicalities do not propagate into the future with human memory like we wish, but knowing intuitively that the "fraction part is tossed away" you can derive the technical points. Technicalities are a heavy burden, but intuition is light and refreshing as the wind, I'll carry those far and wide and when necessary I'll know where to start. Like that paper you linked, thank you.
    • Picaud Vincent
      Picaud Vincent almost 5 years
      I answered here with the emphasis on the Euclidean division (inter-play between integer division and modulus operator).
    • Gabriel Staples
      Gabriel Staples over 4 years
      Related: doing integer division with rounding to nearest whole integer, instead of truncating: stackoverflow.com/questions/2422712/…
  • Will A
    Will A over 13 years
    ...unless, of course, you're dividing a negative number by a positive (or v.v.), in which case it'll be the ceiling.
  • Leonid
    Leonid over 13 years
    @dan04: yep floor would be valid only for positive integers :)
  • lornova
    lornova over 13 years
    It is neither flooring nor ceiling, it is truncation of fractional part, it is conceptually different!
  • Martin York
    Martin York over 13 years
    @Will A: No. It is defined as truncation towards zero. Calling it anything else will just add to confusion so please refrain from doing so.
  • Brian
    Brian over 13 years
    At least from a mathematical perspective, truncation towards zero is equivalent to "if > 0 then floor else ceiling." I think just calling it truncation is simpler than calling it floor/ceiling, but either is valid. Regardless, Will A's point is valid: Dirkgently's answer is partially incorrect, since he stated that the OP is right about the result being the floor of the division.
  • supercat
    supercat over 13 years
    I agree with the comment wondering whether having (neg % pos) go negative is ever useful? On a related note, I wonder if the required arithmetically-incorrect behavior in some cases of "unsignedvar > signedvar" is ever useful? I can understand the rationale for not requiring always-correct behavior; I see no rationale for requiring wrong behavior.
  • R.. GitHub STOP HELPING ICE
    R.. GitHub STOP HELPING ICE over 13 years
    +1 for an excellent reference on why flooring is the correct behavior for integer division (contrary to C's definition, which is broken and almost-never useful).
  • Philip Potter
    Philip Potter over 13 years
    Is this behaviour in C89 as well? I seem to remember modulus is not as rigorously defined.
  • David Thornley
    David Thornley over 13 years
    @Philip Potter: I don't think it was defined in C89, and it isn't in the 1998 C++ standard. In those, of course (a / b) * b + a % b == a had to be satisfied, and the absolute value of a % b had to be less than a, but whether a % b was negative for negative a or b was not specified.
  • Todd Lehman
    Todd Lehman over 9 years
    Even if it's defined as truncation towards zero, it's still the floor operation in the non-negative case and ceiling operation in the non-positive case. They're equivalent definitions. Which definition is clearer to think about depends on what you're doing. Sometimes it's more convenient to think of it in terms of floor and ceiling, and sometimes it's more convenient to think of it in terms of truncation.
  • Ciro Santilli OurBigBook.com
    Ciro Santilli OurBigBook.com over 7 years
    And C99 draft N1256 foreword paragraph 5 mentions reliable integer division as a new language feature. Amazing *-*.
  • Tim Seguine
    Tim Seguine over 7 years
    Why does this have so many upvotes? It gives the wrong answer then quotes the part of the standard that directly contradicts the answer. It doesn't matter if you can define truncation in terms of floor. The answer to the question "Will result always be the floor of the division?" is unequivocally "no"
  • Peter Cordes
    Peter Cordes over 6 years
    Truncation is how most common CPU hardware (e.g. x86) behaves, so it would be crazy to make a different choice. IDK which came first, Fortran semantics or hardware behaviour, but it's not a coincidence that those are the same, too.
  • hobbs
    hobbs over 6 years
    @supercat Consider: filtered = (k - 1) * filtered + value + carry; carry = filtered % factor; filtered /= factor, iterated with changing values of value. It makes a nice integer approximation to a first-order lowpass filter with time constant k... but it's only symmetric if division is truncating and carry gets negative values. Both behaviors for division come in handy from time to time.
  • supercat
    supercat over 6 years
    @hobbs: I don't think the above code would behave cleanly when signals cross zero. If div is a floored division operator and factor is odd, then filtered += (filter+(factor div 2)) div factor would yield clean and symmetrical behavior for all values up to INT_MAX-(factor div 2).
  • hobbs
    hobbs over 6 years
    @supercat it does work though; that code is only slightly distilled from something I've had running in the controller of an atomic clock for a while.
  • supercat
    supercat over 6 years
    @hobbs: For any given value of filtered carry, and factor, there will be "factor" values that yield each possible output value that is strictly between the minimum and maximum possible outputs, except that there will be 2*factor+1 values that yield an output value of zero.
  • supercat
    supercat almost 6 years
    @PeterCordes: Most common CPU hardware could do floored division by most constants faster than they could do truncating division. IMHO, it would have been better for the Standard to say that expr1 / expr2 and expr1 % expr2 must be consistent with each other when both instances of expr1 combine the same objects in the same way, and likewise for expr2, but the choice of truncating versus floored division is otherwise Unspecified. That would have allowed more efficient code generation without breaking much compatibility (and implementations could document specific behavior if inclined)
  • Timothy L.J. Stewart
    Timothy L.J. Stewart over 5 years
    Everyone keeps saying "truncate toward zero" or "ceiling" or "floor" like the code is making a deliberate decision on which technique to use. If the code could talk it would say "I just throw the dam fraction part in the trash and move on with life"