I am using GMP in C. Is it possible to set a mpz_t to the value of a float?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes, there’s a function
mpz_set_dthat you can use for this purpose:The float will be upgraded to a double by C itself and then GMP will turn that into an
mpz_ttype for you.But you should be aware that
mpz_tis an integer type, so you may lose precision. If you’re just using the floats to hold integers larger than yourlongtype, 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:
Note the use of the combined
mpz_init_set_d (num, f)to simplify the code. This is equivalent to the two statements:The program above outputs: