I am using GMP in C. Is it possible to set a mpz_t to the value of a float?
+2
A:
Yes, there's a function mpz_set_d
that you can use for this purpose:
void mpz_set_d (mpz_t rop, double op);
The float will be upgraded to a double by C itself and then GMP will turn that into an mpz_t
type for you.
But you should be aware that mpz_t
is an integer type, so you may lose precision. If you're just using the floats to hold integers larger than your long
type, that should be fine.
If you want to handle actual floating point values, you should probably be using mpf_t
.
To expand, here's some sample code and output:
#include <stdio.h>
#include <values.h>
#include <gmp.h>
int main (void) {
float f = MAXFLOAT;
mpz_t num;
mpz_init_set_d (num, f);
printf ("Max float: %f\n", f);
printf ("As mpz_t : ");
mpz_out_str (stdout, 10, num);
putchar ('\n');
return 0;
}
Note the use of the combined mpz_init_set_d (num, f)
to simplify the code. This is equivalent to the two statements:
mpz_init (num);
mpz_set_d (num, f);
The program above outputs:
Max float: 340282346638528859811704183484516925440.000000
As mpz_t : 340282346638528859811704183484516925440
paxdiablo
2010-05-08 00:21:10
Thanks, yes I did want to truncate decimals. However now I realize I should be using doubles instead of floats.
Full Decent
2010-05-08 20:35:37