Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Narrowing conversion from double to float: is overflow behaviour guaranteed?

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?

like image 265
Sideshow Bob Avatar asked Jul 19 '13 16:07

Sideshow Bob


People also ask

Can a float be converted to a double?

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));

Is int to float narrowing?

- 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.


1 Answers

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.

like image 81
Pascal Cuoq Avatar answered Nov 11 '22 13:11

Pascal Cuoq