开发者

How to extract base 10 mantissa and exponent using gpmlib in C++

开发者 https://www.devze.com 2023-03-11 18:22 出处:网络
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

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 n开发者_运维知识库ot sure how to this library.

Please share some sample code using this library.


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
0

精彩评论

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