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
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.
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.
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.
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.
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With