Inverting Frexp With Ldexp
If I understand the documentation correctly, we should be able to use ldexp to recover a floating point number decomposed into a signed mantissa and an exponent by frexp. I have be
Solution 1:
Modify your C++ program by including the typeinfo
header and inserting the following lines right before the calls to compare
in your test_ldexp
function.
std::cout << "types:" << std::endl;
std::cout << " x : " << typeid(x).name() << std::endl;
std::cout << " mantissa : " << typeid(frexp(x, &exponent)).name()
<< std::endl;
std::cout << " ldexp(...): " << typeid(ldexp(x, 0)).name() << std::endl;
std::cout << " ldexp(...): " << typeid(ldexp(mantissa, exponent)).name()
<< std::endl;
The output is now:
max=3.402823466385288598117042e+38, max_exp=128, max_10_exp=38,
min=1.175494350822287507968737e-38, min_exp=-125, min_10_exp=-37, dig=6,
mant_dig=24, epsilon=1.1920928955078125e-07, radix=2, rounds=1
types:
x : f
mantissa : d
ldexp(...): d
ldexp(...): d
1.000000119209289550781251.00000011920928955078125 (equal)
1.000000119209289550781251.00000011920928955078125 (equal)
max=1.797693134862315708145274e+308, max_exp=1024, max_10_exp=308,
min=2.225073858507201383090233e-308, min_exp=-1021, min_10_exp=-307, dig=15,
mant_dig=53, epsilon=2.220446049250313080847263e-16, radix=2, rounds=1
types:
x : d
mantissa : d
ldexp(...): d
ldexp(...): d
1.0000000000000002220446051.000000000000000222044605 (equal)
1.0000000000000002220446051.000000000000000222044605 (equal)
max=1.189731495357231765021264e+4932, max_exp=16384, max_10_exp=4932,
min=3.362103143112093506262678e-4932, min_exp=-16381, min_10_exp=-4931, dig=18,
mant_dig=64, epsilon=1.084202172485504434007453e-19, radix=2, rounds=1
types:
x : e
mantissa : d
ldexp(...): d
ldexp(...): d
1.000000000000000000108421 (unequal)
1.000000000000000000108421 (unequal)
frexpr
and ldexpr
are returning double
s no matter what type you put in! It appears that you are using the functions defined in math.h
(see here and here) instead those defined in cmath
. Replace your calls to frexpr
and ldexpr
with calls to std::frexpr
and std::ldexpr
and your code will work as you expect.
Post a Comment for "Inverting Frexp With Ldexp"