GMP rounding algorithm

Paul Zimmermann Paul.Zimmermann at loria.fr
Wed Apr 1 09:45:31 CEST 2009


       Emma,

> I have a question about the rounding algorithm of GMP.
> 
> This is part of my code:
> 
> mpf_t f;
> 
> char* pchStr = "99999999985";
> 
> mpf_init_set_str (f,pchStr,10);
> char *ch = mpf_get_str(NULL,&exp,10,10,f);
> 
> The reuslt is supposed to be
> 
> ch = "9999999999"
> 
> but actually it is "9999999998"
> 
> Would anybody tell me why and which rounding algorithm the gmp lib uses?
> 
> Regards,
> 
> Emma

the documentation of mpf_get_str does not say which rounding algorithm is used.
However I cannot reproduce your example with GMP 4.2.4, I get "9999999999" with
the program below, both on a 32-bit and a 64-bit machine:

crumble% gcc -static e.c -lgmp
crumble% ./a.out
gmp_version=4.2.4
VERSION=4.2.4
ch=9999999999

Which version of GMP do you use?

Paul Zimmermann

PS: if you want a full control of rounding, I suggest you use the MPFR library.

#include <stdio.h>
#include "gmp.h"

int main()
{
  mpf_t f;

  char* pchStr = "99999999985";
  mp_exp_t exp;

  printf ("gmp_version=%s\n", gmp_version);
  printf ("VERSION=%d.%d.%d\n", __GNU_MP_VERSION, __GNU_MP_VERSION_MINOR,
          __GNU_MP_VERSION_PATCHLEVEL);
  mpf_init_set_str (f, pchStr, 10);
  char *ch = mpf_get_str (NULL, &exp, 10, 10, f);
  printf ("ch=%s\n", ch);
  mpf_clear (f);
}


More information about the gmp-discuss mailing list