**Next message:**Xavier Leroy: "Re: ocaml et Unix"**Previous message:**Xavier Leroy: "Re: RE : RE :Graphisme"**Next in thread:**Damien Doligez: "Re: Is this OK?"**Messages sorted by:**[ date ] [ thread ] [ subject ] [ author ]

Date: Mon, 18 May 1998 14:51:54 +0200

From: Xavier Leroy <Xavier.Leroy@inria.fr>

To: N Hur <mapnh@maths.bath.ac.uk>, caml-list@inria.fr

Subject: Re: Is this OK?

In-Reply-To: <Pine.SUN.3.91.980515135653.27393A-100000@thor.maths.bath.ac.uk>; from N Hur on Fri, May 15, 1998 at 02:02:24PM +0100

*> Why are the two answers below different?
*

*> (* a camllight session *)
*

*> #(-234)/4
*

*> ;;
*

*> - : int = -58
*

*>
*

*> #div_big_int (big_int_of_string "-234") (big_int_of_string "4");;
*

*> - : big_int = -59
*

*> Thanks for advance for any explanation.
*

In computer arithmetic, integer division has never been well specified

for non-positive arguments. There are at least two sensible behaviors:

(a) round towards zero e.g. (-1) / 2 = 0

(b) round towards -infinity e.g. (-1) / 2 = -1

Each of these two behaviors satisfies two of the following three

desirable properties of integer division and modulus, but not all

three:

(1) (-a) / b = a / (-b) = - (a/b)

(2) a = (a/b) * b + (a mod b)

(3) 0 <= a mod b < abs(b)

More precisely, (a) satisfies (1) and (2) but not (3) (the modulus can

be negative), while (b) satisfies (2) and (3) but fails (1).

It is easy to see that (1), (2) and (3) cannot be satisfied

simultaneously anyway, so behaviors (a) and (b) are as good as you'll

ever get.

Most processors implement behavior (a), and therefore most C programs

also follow (a) (though the C reference manual does not fully specify

integer division and modulus for negative arguments, and therefore (a)

and (b) are both legal). Since the Caml bytecode interpreter is a

C program, that's also the behavior you get.

The bignum library uses its own signed arithmetic over big integers,

and elected to implement behavior (b), i.e. round towards -infinity,

thus ensuring that the modulus is always positive. The reason for

this choice, I guess, is that (b) is much better than (a) if you're

doing modulo arithmetic.

So, there is basically no solution to this problem, except providing

two division operations and two modulus operations, one set following

(a) and the other following (b).

- Xavier Leroy

**Next message:**Xavier Leroy: "Re: ocaml et Unix"**Previous message:**Xavier Leroy: "Re: RE : RE :Graphisme"**Next in thread:**Damien Doligez: "Re: Is this OK?"**Messages sorted by:**[ date ] [ thread ] [ subject ] [ author ]

*
This archive was generated by hypermail 2b29
: Sun Jan 02 2000 - 11:58:14 MET
*