When casting double infinity to float and vice versa, will it still be infinity? Is it the same with NaN?
-
2related/dupe: stackoverflow.com/questions/14773142/… – NathanOliver Apr 6 at 13:05
-
6@NathanOliver: Strictly speaking that covers only half the cases asked here. In IEEE754, there are many more 64-bit NaN's than there are 32 bit NaN's, so it matters if you start with 32 or 64 bits. The linked question assumes you start with 32 bits; this question also considers the case where you start with one of the 64 bit NaN's. And since there are more than 4 billion 64-bit NaN's, the pigeonhole principle tells us that you cannot preserve the NaN payload (the exact binary NaN representation) – MSalters Apr 6 at 19:13
Converting any float to a double is guaranteed to preserve the value. Converting a double to float is guaranteed to preserve the value if the original value is representable as float.
If your system conforms to IEEE-754, then float is able to represent infinity and NaN. Otherwise, you can use <numeric_limits>
to check whether that is the case. The payload of a double NaN is not necessarily representable by a float NaN.
-
8There may be no support for NaN payloads, because that is an optional feature in IEEE-754 (a should-provision, not a shall-provision). For example, when running CUDA on a GPU, the double-precision hardware supports NaN payloads, while single-precision hardware produces a single canonical NaN (
0x7fffffff
). But in adouble
tofloat
conversion, a NaN stays NaN. – njuffa Apr 6 at 21:32