When casting double infinity to float and vice versa, will it still be infinity? Is it the same with NaN?
Does casting to or from a double and a float preserve infinity and NaN?
Asked Answered
related/dupe: #14773642 –
Rollicking
@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
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.
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.