Precision loss from float to double, and from double to float?

float fv = orginal_value; // original_value may be any float value ... double dv = (double)fv; ... fv = (float)dv; 

SHOULD the fv value be equal to the original value? Can any accuracy be lost?

+6
source share
1 answer

SHOULD the fv value be equal to the original value? Any accuracy could be lost?

Yes, if the dv value has not changed between them.

From Conversion 6.3.1.5 Real Floating Types in C99 Specifications:

  • When a float advances to double or long double, or double advanced to long double, its value does not change .
  • When a double is downgraded to swimming, the long double is halved or floats, or the value is presented in greater accuracy and range than is required by its semantic type (see 6.3.1.8) is explicitly converted to its semantic type , if the converted value can be represented exactly in the new type it has not changed. If the converted value is in a range of values ​​that can be represented but cannot be represented accurately, the result will be either the closest higher or the closest lower represented value selected in accordance with the implementation. If the value being converted is outside the range of the values ​​that may be represented, undefined behavior

For C ++ from section 4.6 aka conv.fpprom (draft used: n337 , and I find the lines similar are available in the final specification)

A value of type float can be converted to a prvalue of type double. The value does not change . This conversion is called floating point promotion.

And section 4.8 aka conv.double

A floating point type value can be converted to a prvalue of another floating point type. If the source value can be exactly represented in the destination type , the result of the conversion is that exact representation. If the source value is between two adjacent target values, the result of the conversion is the implementation-specific selection of any of these values. Otherwise, the behavior is undefined. Conversions permitted as floating point promotions are excluded from the set of floating point conversions

Values ​​must be exactly equal.

+14
source

All Articles