Reputation: 4339
I'm writing a few functions that will convert float/double to fixed point and back. Does anyone know the best way to determine the number of bits used for the exponent portion of a float or double? I was hoping to using something from std::numeric_limits, but have had no luck.
Is the exponent part defined by the C++ standard or is it compiler/machine specific? Or can it vary at runtime?
Upvotes: 2
Views: 767
Reputation: 3909
The characteristics of floating point numbers depend on the machine architecture. It does not vary at runtime. Have a look at the header <cfloat> of your compiler, it should have the details.
But you can also dive into the machine yourself:
The book Numerical Recipes in C by W.H. Press et al. contains a program named machar.c
in chapter 20.1 (Less-numerical algorithms) to detect the machine's floating point capabilities without assuming anything from standard library headers. It's also available online.
Upvotes: 0
Reputation: 52294
What is missing from numeric_limits<>::{min_exponent, max_exponent}? (They are constrained to give the answer for normalized numbers, if that doesn't suit you, combine with denorm
and digits
).
Upvotes: 1
Reputation: 75130
If float
on that platform is encoded in IEC-559 (a.k.a. IEEE 754 in the United States), then it will always be 8 bits. If the double
of that platform is encoded with IEC-559 (or whatever the 64 bit version is) then it will always be 11. If not, then you can't even assume it stores the exponent.
While the Standard doesn't specify in what format floating point numbers should be stored, in C++11 (and C++03?) you can test if float
or double
conforms to IEC-559 by using numeric_limits<T>::is_iec559
(where T
is a floating-point type):
#include <limits>
cout << "float is IEC-559? " << numeric_limits<float>::is_iec559 << endl
<< "double is IEC-559? " << numeric_limits<double>::is_iec559 << endl;
Upvotes: 6