mini-gmp

Vincent Lefevre vincent at vinc17.net
Fri Jan 17 08:52:03 UTC 2014


On 2014-01-16 21:38:56 +0100, Niels Möller wrote:
> Zimmermann Paul <Paul.Zimmermann at inria.fr> writes:
> 
> > 2) I had to add a line:
> >    unsigned int mp_bits_per_limb = GMP_NUMB_BITS;
> 
> I just added this to mini-gmp, or more precisely 
> 
>   const int mp_bits_per_limb = GMP_LIMB_BITS;
> 
> It's signed, just like in gmp, I have no idea why unsigned is not used.

IMHO, if a non-negative value fits in a signed type and is regarded
more as an element of the ring of integers Z than a bit array (said
otherwise, it will be used in arithmetic expressions), then the type
should be signed. The reason is that if you have an expression like

  int some_int, expr;
  /* ... */
  expr = mp_bits_per_limb - some_int;

that can be negative, then you'll get the correct negative value.
If mp_bits_per_limb were an unsigned int, then the subtraction
would be unsigned and one would get a positive value instead of a
negative one (unsigned int type). When stored to expr (signed int
type), one would generally get the correct negative value, but
this is not portable; in particular things may break with some
optimizations or on some platforms. Moreover this is particularly
dangerous. Imagine that in the future, expr is changed to

  long expr;

Then, on some platforms, one would get a large positive value
instead of the correct negative value.

In MPFR, we got these kinds of problems when mpfr_prec_t was unsigned,
in particular because of add/sub operations between precisions
(unsigned), exponents (signed), and some other kinds of values such
as bit counts. The presence of unsigned types (in particular the
precisions) lead to unportable code and wrong results on 64-bit
machines (which were rather new at that time). That's why we chose
to change the mpfr_prec_t type to a signed type for MPFR 3.0.0.

-- 
Vincent Lefèvre <vincent at vinc17.net> - Web: <http://www.vinc17.net/>
100% accessible validated (X)HTML - Blog: <http://www.vinc17.net/blog/>
Work: CR INRIA - computer arithmetic / AriC project (LIP, ENS-Lyon)


More information about the gmp-devel mailing list