1

I'm having trouble following the documentation for GMP https://gmplib.org/manual/C_002b_002b-Interface-Floats there is no examples for what I want to do. It might be more than 1 question but I don't think that they are too long for having 4 individual questions asking for each answer.

  1. How can I initialize a mpf_class with 20 decimal places of precision

  2. How can I set a value to my mpf_class with any precision I want, eg: mpf_class myNum = 3.1415926535897932000000000000000000000000123456789

  3. How can I make an std::string hold the value of my mpf_class with the precision (lets say my std::string holds exactly the number above (3.14...)

  4. From my understanding with gmp (without the mpf_class) you need to manage the memory, ie, mpf_clear() is there any memory managment that I need to do with mpf_class? If so what are they?

Ggsgn Hdjwngnf
  • 133
  • 2
  • 10

1 Answers1

1

There are plenty of pretty nice examples in the GMP distribution itself, just look at the tests/ directory. Or in here, just search for the tag gmp and refine.

  1. Note that to represent a decimal number in binary you need roughly speaking about log(10)/log(2) = 3.322... times binary digits than that of decimal digits. So, you use

    Function: void mpf_class::set_prec (mp_bitcnt_t prec)

after delcaring the class instance, with precision set to 20 * 3.322, and GMP will alloc enough space for that to fit, and a little bit more, to fill in the integer number of limbs.

  1. To initialize a mpf_t variable to arbitrary precision you can't use numeric constants in C/C++, like your example, because those numeric literals are interpreted as float or double according to your platform, and might not have the desired precision. In C++, use instead the string overload assignment, like so: mpf_class myNum; myNum = "3.1415926535897932000000000000000000000000123456789". C++ overload will call the mpf_init_set_str behind the scenes for you.

  2. As above, but note that conversion from decimal to binary float has subtleties, see for example here and here. So, you have to understand what accuracy your decimal numbers have, and perhaps have a tolerance compare if required to do so (see my answer here).

  3. With mpf_class you need to just declare the object instance and then delete it if you need to clear memory. With mpf_t you need to call mpf_init(), for example, and after using it, call mpf_clear() if needed. Note that all of those will be cleared from memory at program exit, as per operating system standards. You only need to worry about memory allocation, with malloc and free, and the alike, if you use the mpn_ raw "difficult to use" functions.

Arc
  • 412
  • 2
  • 16