mpf_set_str doesn't seem to work for numbers with + prefix

Marc Glisse marc.glisse at inria.fr
Mon Sep 26 22:39:09 CEST 2011


On Sat, 17 Sep 2011, Ronald Bruck wrote:

> I've tried the following program in both Linux (SuSE 11.4, GMP 5.0.2) and Mac OS X (10.7 "Lion", GMP 5.0.2):
>
> #include <stdio.h>
> #include <gmp.h>
>
> int main()
> {
>  mpf_t fx;
>  double x;
>  int ch;
>  char str[128];
>
>  mpf_init2 (fx, 64);
>
>  while (((ch = fgetc(stdin)) != EOF)&&(ch != '\n')) {
>    ungetc (ch, stdin);
>    scanf ("%s", str);
>    sscanf (str, "%lf", &x);
>    mpf_set_str (fx, str, 10);
>    gmp_printf ("x = %lf fx = %Fg str = '%s'\n", x, fx, str);
>  }
> }
>
> If I try it on an input line of "+5.179" the output is
>
> x = 5.179000 fx = 0 str = '+5.179'
>
> This is completely unexpected behavior; "+5.179" is a perfectly legal format for a real number, and may easily be read in the output of another C program which uses a "%+.3lf" format string, for example.  (That's usually done for alignment reasons.)
>
> When GMP reads a number with a preceding "+" sign, it returns 0.  Same deal with mpf_inp_str.  Is this documented?  Shouldn't it be fixed?  (But first, is this what others observe?)
>
> The bug--if bug it is--bit me VERY hard recently, when my program suite suddenly quit working correctly.

I couldn't find a mention of this in the public documentation. It is 
documented in the code though; scanf has this comment:
       /* don't store '+', it's not accepted by mpz_set_str etc */
so it doesn't look like an accident.

I just found this:
http://gmplib.org/list-archives/gmp-bugs/2008-May/001007.html

which seems to say that this behavior might change (lack of time being one 
of the main obstacles).

-- 
Marc Glisse


More information about the gmp-bugs mailing list