Does casting to or from a double and a float preserve infinity and NaN?
Asked Answered
D

1

23

When casting double infinity to float and vice versa, will it still be infinity? Is it the same with NaN?

Drive answered 6/4, 2021 at 13:0 Comment(2)
related/dupe: #14773642Rollicking
@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)Malaise
E
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.

Expressive answered 6/4, 2021 at 13:7 Comment(1)
There 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.Rhodes

© 2022 - 2024 — McMap. All rights reserved.