0

I need to extract significand and exponent of a double in C++ using gpmlib.
Ex: double a = 1.234;
I would like to extract 1234 as significand and 3 as exponent so that a = 1234e-3. I heard that gpmlib supports this type functions. I am not sure how to this library.

Please share some sample code using this library.

4

1 回答 1

1

It seems that you're looking for mpf_class::get_str(), which will break up the floating-point value 1.234 into the string "1234" and the exponent 1, because 1.234 == 0.1234 * 10^1

You will need to subtract the size of the string from that exponent, to fit your requirements.

#include <iostream>
#include <string>
#include <gmpxx.h>
int main()
{
    double a = 1.125; // 1.234 cannot be stored in a double exactly, try "1.234"
    mpf_class f(a);
    mp_exp_t exp;
    std::string significand = f.get_str(exp);
    std::cout << "significand = " << significand
              << " exponent = " << exp-(int)significand.size() << '\n';

}

This prints

~ $ ./test
significand = 1125 exponent = -3
于 2011-06-08T17:51:15.880 回答