c++ - Is round-trip through floating point always defined behavior if floating point range is bigger? -
let's have 2 arithmetic types, integer one, i
, , floating point one, f
. assume std::numeric_limits<i>::max()
smaller std::numeric_limits<f>::max()
.
now, let's have positive integer value i
. because representable range of f
larger i
, f(i)
should defined behavior.
however, if have floating point value f
such f == f(i)
, i(f)
defined? in other words, i(f(i))
defined behavior?
relevant section c++14 standard:
4.9 floating-integral conversions [conv.fpint]
- a prvalue of floating point type can converted prvalue of integer type. conversion truncates; is, fractional part discarded. behavior undefined if truncated value cannot represented in destination type. [ note: if destination type
bool
, see 4.12. — end note ]- a prvalue of integer type or of unscoped enumeration type can converted prvalue of floating point type. result exact if possible. if value being converted in range of values can represented value cannot represented exactly, implementation-defined choice of either next lower or higher representable value. [ note: loss of precision occurs if integral value cannot represented value of floating type. — end note ] if value being converted outside range of values can represented, behavior undefined. if source type
bool
, valuefalse
converted 0 , valuetrue
converted one.
however, if have floating point value
f
suchf == f(i)
,i(f)
defined? in other words,i(f(i))
defined behavior?
no.
suppose i
signed two's complement 32 bit integer type, f
32 bit single precision floating point type, , i
maximum positive integer. within range of floating point type, cannot represented floating point number. of 32 bits used exponent.
instead, conversion integer floating point implementation dependent, typically done rounding closest representable value. rounded value 1 beyond range of integer type. conversion integer fails (better said, it's undefined behavior).
Comments
Post a Comment