Converting MPFR numbers to string and back

Viewed 818

I'm trying to convert MPFR number to string and then back. The code I'm using is:

int base = 10;
int input = 25;

mpfr_t number;
mpfr_inits2(53, number, (mpfr_ptr) 0);
mpfr_set_d(number, input, MPFR_RNDD);
mpfr_printf ("mpfr = %.17Rg\n", number);

char* str = NULL;
mpfr_exp_t e;
str = mpfr_get_str (NULL, &e, base, 0, number, MPFR_RNDN);

cout << "str: " << str << endl;
cout << "e: " << e << endl;

mpfr_t back;
mpfr_inits2(53, back, (mpfr_ptr) 0);
mpfr_set_str(back, str, base, MPFR_RNDD);
mpfr_set_exp(back, e);
mpfr_printf ("back = %.17Rg\n", back);

mpfr_free_str (str);

Which gives me the output:

mpfr = 25
str: 25000000000000000
e: 2
back = 2.7755575615628914

If I change the base to 2, then I get the correct output

mpfr = 25
str: 11001000000000000000000000000000000000000000000000000
e: 5
back = 25

But if I change the input to 0, I again get the wrong mpfr number back:

mpfr = 0
str: 00000000000000000000000000000000000000000000000000000
e: 0
back = 0.8125

What exactly am I doing wrong?

1 Answers
Related