Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find exponent and mantissa of a double to the base 10

Tags:

c++

I need to break numerical values of type double into: exponent and mantissa. I found that I can do this using the frexp() function from math.h. However, this function assumes the base to be 2.

Is there some way by which I may find the exponent and mantissa to the base 10 -- such that both the returned mantissa and exponent are of the type integer.

#include <cstdio>
#include <cmath>

int main()
{
   int e;
   const double x = 1024;
   const double fraction = frexp(x, &e);
   std::printf("x = %.2lf = %.2lf * 2^%d\n", x, fraction, e);
}

The compiler which I have is: gcc (Ubuntu/Linaro 4.6.4-6ubuntu2) 4.6.4

like image 778
Jannat Arora Avatar asked Apr 11 '15 20:04

Jannat Arora


People also ask

How do you find the exponent and mantissa?

To make the calculations easy, the sign of the exponent is not shown, but instead excess 128 numbering system is used. Thus, to find the real exponent, we have to subtract 127 from the given exponent. For example, if the mantissa is “10000000,” the real value of the mantissa is 128 − 127 = 1.

What is mantissa and exponent example?

In decimal, very large numbers can be shown with a mantissa and an exponent. i.e. 0.12*10² Here the 0.12 is the mantissa and the 10² is the exponent. the mantissa holds the main digits and the exponents defines where the decimal point should be placed. The same technique can be used for binary numbers.

What is exponent and mantissa in floating point?

The mantissa represents the actual binary digits of the floating-point number. The power of two is represented by the exponent. The stored form of the exponent is an 8-bit value from 0 to 255.

What is mantissa in C language?

The C library function double frexp(double x, int *exponent) return value is the mantissa, and the integer pointed to by exponent is the exponent. The resultant value is x = mantissa * 2 ^ exponent.


1 Answers

Basic logarithms will help. The idea is to use std::log10 to get the exponent and then divide the original number by 10^exp to get the mantissa.

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));    
}
like image 123
sbabbi Avatar answered Oct 23 '22 04:10

sbabbi