找到以 10 为底的双倍的指数和尾数

Find exponent and mantissa of a double to the base 10

本文关键字:指数      更新时间:2023-10-16

我需要将双倍类型的数值分解为:指数和尾数。我发现我可以使用 math.h 中的 frexp() 函数来做到这一点。但是,此函数假定基数为 2。

有没有办法让我找到以 10 为底的指数和尾数——这样返回的尾数和指数都是整数类型。

#include <cstdio>
#include <cmath>
int main()
{
   int e;
   const double x = 1024;
   const double fraction = frexp(x, &e);
   std::printf("x = %.2lf = %.2lf * 2^%dn", x, fraction, e);
}

我拥有的编译器是:gcc(Ubuntu/Linaro 4.6.4-6ubuntu2)4.6.4

基本对数会有所帮助。这个想法是使用std::log10来获取指数,然后将原始数字除以 10^exp 得到尾数。

double frexp10(double arg, int * exp)
{
   *exp = (arg == 0) ? 0 : 1 + (int)std::floor(std::log10(std::fabs(arg) ) );
   return arg * std::pow(10 , -(*exp));    
}