mpq_get_d() rounding for different platforms?

Paul Zimmermann Paul.Zimmermann at loria.fr
Tue Mar 17 18:18:52 CET 2009


> > For example, for the rational 4/5,
> >
> > the MinGW version returns 0.79999999999999993, while the Linux version
> > returns 0.80000000000000004.
> 
> Make sure that the assignment of 4/5 is being carried out in the same way.
> 
> As the following little program demonstrates, mpq_set_str(q, "4/5", 10) and 
> mpq_set_d(q, (double) 4 / 5) assigm different values:
> 
> #############################
> #include <stdio.h>
> #include <gmp.h>
> 
> int main(void) {
>     mpq_t q1;
>     mpq_t q2;
> 
>     mpq_init(q1);
>     mpq_init(q2);
> 
>     mpq_set_str(q1, "4/5", 10);
>     mpq_set_d(q2, (double)4 / 5);
> 
>     printf("%.17f\n", mpq_get_d(q1));
>     printf("%.17f\n", mpq_get_d(q2));
> 
>     mpq_clear(q1);
>     mpq_clear(q2);
>     return 0;
> }
> #############################
> 
> For me (both Linux and MinGW) that outputs:
> 
> 0.79999999999999993
> 0.80000000000000004
> 
> Cheers,
> Rob 

the reason is that in mpq_set_d(q, (double) 4 / 5), you first round 4/5 to the
nearest double precision floating-point number 3602879701896397/2^52, and then
only you convert to rational. See http://www.mpfr.org/faq.html#accuracy.

Paul Zimmermann


More information about the gmp-discuss mailing list