Integer dicision
Paul Hankin
paul.hankin at gmail.com
Fri Apr 11 03:56:05 EDT 2008
On Apr 11, 6:06 am, casevh <cas... at gmail.com> wrote:
> On Apr 10, 9:28 pm, bdsatish <bdsat... at gmail.com> wrote:
>
> > How does (a/b) work when both 'a' and 'b' are pure integers ?
>
> Python defines the quotient and remainder from integer division so
> that a = qb + r and 0<=r < abs(b). C/C++ lets the remainder be
> negative.
On Apr 11, 6:06 am, casevh <cas... at gmail.com> wrote:
> On Apr 10, 9:28 pm, bdsatish <bdsat... at gmail.com> wrote:
>
> > How does (a/b) work when both 'a' and 'b' are pure integers ?
>
> Python defines the quotient and remainder from integer division so
> that a = qb + r and 0<=r < abs(b). C/C++ lets the remainder be
> negative.
On Apr 11, 6:06 am, casevh <cas... at gmail.com> wrote:
> On Apr 10, 9:28 pm, bdsatish <bdsat... at gmail.com> wrote:
>
> > How does (a/b) work when both 'a' and 'b' are pure integers ?
>
> Python defines the quotient and remainder from integer division so
> that a = qb + r and 0<=r < abs(b). C/C++ lets the remainder be
> negative.
(Puts language lawyer hat on)
That's not accurate: r can be negative. To quote the reference manual:
'The modulo operator always yields a result with the same sign as its
second operand (or zero); the absolute value of the result is strictly
smaller than the absolute value of the second operand.'
divmod(9, -2) # (-5, -1)
Both C and Python define q = a / b and r = a % b to satisfy a = q * b
+ r, where -abs(b) < r < abs(b).
Where they differ:
Python: r has the same sign of b (or 0).
C99: r has the same sign as a (or 0).
C89 (Standard C): It's implementation defined what sign r has if
either a or b is negative.
This means python already has C-like behaviour... it's compatible with
standard C, although not with C99.
--
Paul Hankin
More information about the Python-list
mailing list