Integer division, surprising results

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Michael Cornelius

    Integer division, surprising results

    As an old C programmer, I'm surprised by some results I'm getting with
    integer division. For example:
    [color=blue][color=green][color=darkred]
    >>> -1/1000[/color][/color][/color]
    -1[color=blue][color=green][color=darkred]
    >>> -9/2[/color][/color][/color]
    -5

    I expect the results of these expressions to be 0 and -4,
    respectively.

    I've looked at faqs and documentation, and nothing jumped out at me. Can
    anyone explain the reasoning for this?

    Thanks,
    Michael Cornelius


  • Rory Geoghegan

    #2
    Re: Integer division, surprising results

    > I've looked at faqs and documentation, and nothing jumped out at me. Can[color=blue]
    > anyone explain the reasoning for this?[/color]

    According to my math book integer division is defined as such:
    a/b = q, where a = b*q + r and r is the remainder.

    A remainder (ei a modulo) is always positive, effectively flooring all
    the division operations.

    Comment

    • Steve

      #3
      Re: Integer division, surprising results

      Rory Geoghegan wrote:[color=blue][color=green]
      >>I've looked at faqs and documentation, and nothing jumped out at me. Can
      >>anyone explain the reasoning for this?[/color]
      >
      >
      > According to my math book integer division is defined as such:
      > a/b = q, where a = b*q + r and r is the remainder.
      >
      > A remainder (ei a modulo) is always positive, effectively flooring all
      > the division operations.[/color]

      Remainders are always positive, but modulo can be
      defined as either positive or negative (for negative
      arguments). There are pros and cons for doing it either
      way, although the Python way seems to have more pros
      than cons.


      --
      Steven D'Aprano


      Comment

      Working...