When casting double infinity to float and vice versa, will it still be infinity? Is it the same with NaN?
Asked
Active
Viewed 1,499 times
23
-
2related/dupe: https://stackoverflow.com/questions/14773142/is-a-float-guaranteed-to-be-preserved-when-transported-through-a-double-in-c-c – NathanOliver Apr 06 '21 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 06 '21 at 19:13
1 Answers
27
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.

eerorika
- 232,697
- 12
- 197
- 326
-
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 a `double` to `float` conversion, a NaN stays NaN. – njuffa Apr 06 '21 at 21:32