tags:

views:

57

answers:

1

I'm attempting to store the value 0.9999 into an mpfr_t variable using the mpfr_set_str() function

But 0.9999 is rounded to 1 (or some other value != 0.9999) during storage, no matter the round value (GMP_RNDD, GMP_RNDU, GMP_RNDN, GMP_RNDZ)

So what's the best method to store 0.9999 in an mpfr_t variable using mpfr_set_str()? Is it possible?

Here is my test program, it prints "buffer is: 1", instead of the wanted "buffer is: 0.9999":

int main()
{

    size_t precision = 4;
    mpfr_t mpfrValue;

    mpfr_init2(mpfrValue, precision);
    mpfr_set_str(mpfrValue, "0.9999", 10, GMP_RNDN);

    char *buffer = (char*)malloc((sizeof(char) * precision) + 3);
    mp_exp_t exponent;

    mpfr_get_str(buffer,
                 &exponent,
                 10,
                 precision,
                 mpfrValue,
                 GMP_RNDN);

    printf("buffer is: %s\n", buffer);

    free(buffer);
    mpfr_clear(mpfrValue);

    return 0;
}

Thanks for the help

+1  A: 

precision is given in bits, not in decimal digits, as you seem to be assuming. It seems that you can reprint the correct value to 4 decimal digits with 15 bits precision. Also, you can output directly using mpfr_printf.

If you do need to use mpfr_get_str, I would pass null as the first parameter. If you do that the string is allocated for you. Then, to free it you call mpfr_free_str.

int main()
{
    size_t precision = 15;
    mpfr_t mpfrValue;

    mpfr_init2(mpfrValue, precision);
    mpfr_set_str(mpfrValue, "0.9999", 10, GMP_RNDN);

    mpfr_printf("Value is: %Rf\n", mpfrValue);
    mpfr_clear(mpfrValue);
    return 0;
}
Matthew Flaschen
Thank you, it's working now.
Silmaersti