I have a program that reads numbers from a string to an mpz_t and then converts it to an mpf_t. Despite of being read correctly from the file, there is a precision loss when I convert them to mpf_t. The code is the following:
#include <gmp.h>
#include <stdlib.h>
#include <stdio.h>
int main (int argc, char **argv) {
char* str = "632512364206354367378453";
mpz_t x;
mpz_init_set_str(x, str, 10);
mpf_t a;
mpf_init(a);
mpf_set_z(a, x);
gmp_printf("mpz_t: %Zd\n", x);
gmp_printf("mpf_t: %Ff\n", a);
}
The output for this example is:
mpz_t: 632512364206354367378453
mpf_t: 632512364206354367378000.000000
As you can see the last 3 digits are not correct. How can I avoid this? Is there any other function to perform this conversion?
Thanks
From the manual page:
Function: void mpf_init (mpf_t x)
Initialize x to 0. Normally, a variable should be initialized once only or at least be cleared, using mpf_clear, between initializations. The precision of x is undefined unless a default precision has already been established by a call to mpf_set_default_prec.
There's your problem.
Solution:
Function: void mpf_init2 (mpf_t x, mp_bitcnt_t prec)
Initialize x to 0 and set its precision to be at least prec bits. Normally, a variable should be initialized once only or at least be cleared, using mpf_clear, between initializations.
That way, you can use the prec
precision count argument to specify how many bits of precision you want.