From float to mpz_t

I use GMP in C. Is it possible to set mpz_t to a float value?

+4
source share
1 answer

Yes, there is a mpz_set_d function that you can use for this purpose:

 void mpz_set_d (mpz_t rop, double op); 

The float will be upgraded to double from C itself, and then GMP will turn this into mpz_t type for you.

But you should know that mpz_t is an integer type, so you may lose precision. If you just use a float to store integers larger than your long type, this should be fine.

If you want to handle the actual floating point values, you should probably use mpf_t .


To expand, here is an example of 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 combined mpz_init_set_d (num, f) to simplify the code. This is equivalent to two statements:

 mpz_init (num); mpz_set_d (num, f); 

Program above outputs:

 Max float: 340282346638528859811704183484516925440.000000 As mpz_t : 340282346638528859811704183484516925440 
+5
source

Source: https://habr.com/ru/post/1309167/


All Articles