开发者

From float to mpz_t

开发者 https://www.devze.com 2022-12-30 02:18 出处:网络
I am using GMP in C. Is it possible to set a mpz_t to the value of a f开发者_如何学Pythonloat?Yes, there\'s a function mpz_set_d that you can use for this purpose:

I am using GMP in C. Is it possible to set a mpz_t to the value of a f开发者_如何学Pythonloat?


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号