If I try this
float f = (float)numeric_limits<double>::infinity();
Or indeed, try to cast anything bigger than float max down to a float, am I guaranteed to end up with infinity?
It works on GCC, but is it a standard though?
A simple solution that works well, is to parse the double from the string representation of the float: double val = Double. valueOf(String. valueOf(yourFloat));
- in this sense it is called narrowed. Though float has wider range than int, it has less precision. Besides, floating point representation is approximation - that is, it does not represent exact number (except for power of 2). In that sense, the int is also narrowed.
float f = (float)numeric_limits<double>::infinity();
This is guaranteed to set f
to infinity if your compilation platform offers IEEE 754 arithmetic for floating-point computations (it usually does).
Or indeed, try to cast anything bigger than float max down to a float, am I guaranteed to end up with infinity?
No. In the default IEEE 754 round-to-nearest mode, a few double
values above the maximum finite float
(that is, FLT_MAX
) convert to FLT_MAX
. The exact limit is the number midway between FLT_MAX
(0x1.fffffep127
in C99 hexadecimal representation) and the next float
number that could be represented if the exponent in the single-precision format had a larger range, 0x2.0p127
. The limit is thus 0x1.ffffffp127
or approximately 3.4028235677973366e+38 in decimal.
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