Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!henry From: henry@utzoo.UUCP (Henry Spencer) Newsgroups: net.lang.c Subject: Re: modulus fn with negatives Message-ID: <4294@utzoo.UUCP> Date: Sat, 8-Sep-84 19:12:47 EDT Article-I.D.: utzoo.4294 Posted: Sat Sep 8 19:12:47 1984 Date-Received: Sat, 8-Sep-84 19:12:47 EDT References: <212@digi-g.UUCP>, <1011@drutx.UUCP> Organization: U of Toronto Zoology Lines: 24 The basic problem here is simple: there is no unique way to turn a non-integer result of integer division into a pair, where both quotient and remainder are integers. There are at least four different ways to do this (truncate quotient towards zero, truncate toward minus infinity, truncate to give positive remainder, rounding with some sort of tie-breaking rule). Several of these give the same answer when all numbers are positive, but negative numbers expose the differences. Fortran picked, more or less arbitrarily, truncate-towards-zero, and many machines have followed its lead, but that's by no means universal. Note that two's-complement arithmetic shifts implement truncate-towards- minus-infinity division, not truncate-towards-zero. The current draft of the ANSI C standard explicitly states that either truncate-towards-zero or truncate-towards-minus-infinity is legitimate, and the choice is implementation-dependent. The only safe rule is to avoid integer division with negative operands, unless you don't care about the rounding behavior. Portable programs should not depend on the rounding behavior of integer division. -- Henry Spencer @ U of Toronto Zoology {allegra,ihnp4,linus,decvax}!utzoo!henry