apadana
apadana

Reputation: 722

What happens when casting double to float?

Suppose that the closest float values to a double value d are f1 and f2, so that f1 < d < f2. Which will be the result of casting d to float in C99? f1 or f2? Consider these two cases:

  1. if d - f1 > f2 - d
  2. if d - f1 < f2 - d

I have assumed that d itself cannot be represented by any float value exactly.

Upvotes: 2

Views: 761

Answers (1)

Eric Postpischil
Eric Postpischil

Reputation: 222302

C 2018 6.3.1.5 discusses conversions between real floating types and says:

… If the value being converted is in the range of values that can be represented but cannot be represented exactly, the result is either the nearest higher or nearest lower representable value, chosen in an implementation-defined manner.

Common C implementations use round-to-nearest by default, with ties rounded to the candidate with the even low bit.

The rounding mode is reported by FLT_ROUNDS, declared in <float.h> and specified in 5.2.4.2.2 9:

The rounding mode for floating-point addition1 is characterized by the implementation-defined value of FLT_ROUNDS:

−1 indeterminable

0 toward zero

1 to nearest

2 toward positive infinity

3 toward negative infinity

The round mode may be changed by the fesetround function declared in <fenv.h>, although support for it and the FENV_ACCESS pragma it requires are spotty.

The C standard also provides Annex F that C implementations may adopt. In that case, the default rounding mode during compilation and execution is round-to-nearest ties-to-even per F.8.2 1:

During translation the IEC 60559 default modes are in effect:

— The rounding direction mode is rounding to nearest…

and F.8.3 1:

At program startup the floating-point environment is initialized as prescribed by IEC 60559:

— The rounding direction mode is rounding to nearest.

My understanding is IEC 60559 is functionally equivalent to IEEE 754.

Footnote

1 I suspect “addition” is an error in the standard and is intended to be “arithmetic.”

Upvotes: 6

Related Questions