tags:

views:

182

answers:

2

I am using GMP, and I want to be able to quickly convert an mpz to an mpf. I looked through the library and couldn't find much. The best thing I could think of was this:

mpz_t x;
/* Insert code here that assigns some value to x */
char buf[SIZE];
gmp_sprintf(buf, "%Zd", x);
mpf_t y;
mpf_set_str(y, buf);

This solution requires repeated conversion to and from a string. Also, it is limited by SIZE, and I see no way to predetermine how large SIZE needs to be. Is there any better way to do this conversion?

+3  A: 

What about using mpf_set_z (mpf_t rop, mpz_t op) ?

Also (I assume you've done this) your mpz and mpf variables will need initialising with mpf_init(mpf_t x) and mpz_init(mpz_t x).

So you'd do:

mpz_t x;
mpz_init(x);
/* Insert code here that assigns some value to x */
mpf_t y;
mpf_init(y);
mpf_set_z(y,x);
Ninefingers
+1  A: 

Wow, given the bad reputation of sprintf I'm surprised they even included a function like it.

mpz_sizeinbase can be used to figure out how much space you will need to hold a base 10 representation of an integer. And the other person who answered is correct, mpf_set_z is a much better way than converting the integer to a base 10 string and reading it back into a float.

Omnifarious