0

To comply with the interface of a library I have to round a float to a double, and then back to float again, without any additional manipulation in between. I'd need to understand if the final value is guaranteed to be equal (in the sense of ==) to the original float value, or if there are cases when this is a safe assumptions.

Nicola Mori
  • 777
  • 1
  • 5
  • 19
  • "Round a float to a double": why? Why not just assign it? – user207421 Mar 11 '22 at 06:51
  • @user207421: I simplified the description of the problem, the real one is more involved but details are not essential. Anyway, nothing is actually cast but there are just an assignment from float to double and another from double to float. – Nicola Mori Mar 11 '22 at 06:55
  • So nothing is explicitly rounded. So why did you use the term `round`? Please clarify your question. – user207421 Mar 11 '22 at 06:58
  • 1
    With IEEE754 floating-point representation, all single precision floating point values are exactly representable in double-precision. Relevant questions: https://stackoverflow.com/q/14773142/580083, https://stackoverflow.com/q/5777484/580083. C++ standard quote: [The set of values of the type `float` is a subset of the set of values of the type `double`](http://eel.is/c++draft/basic.fundamental#12.sentence-3). – Daniel Langr Mar 11 '22 at 07:07
  • Of course, "equal in the sense of `==`" is not true for NaNs (regardless of any intermediate conversions). – chtz Mar 11 '22 at 07:12

1 Answers1

1

I don't know what do you mean by "rouding" float to double. But if you mean conversion, then, IMO, the value is guaranteed to be preserved.

Relevant parts of the C++ standard:

The set of values of the type float is a subset of the set of values of the type double;...

http://eel.is/c++draft/basic.fundamental#12.sentence-3

A prvalue of floating-point type 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.

http://eel.is/c++draft/conv.double#1.sentence-2

Daniel Langr
  • 22,196
  • 3
  • 50
  • 93