Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any definition how floating-point values evaluated at compile-time are rounded?

Is there any definition how floating-point values evaluated at compile-time are rounded in C or C++ ? F.e. when I have double d = 1.0 / 3.0; ? I.e. what kind of rounding is done at compile-time.

And is there a definition of what's the default-rounding mode for a thread at runtime (C99's / C++11's fegetround() / fesetround()) ?

And is rounding to integer-values also included in the latter configuration parameters ? Im aware of nearbyint(), but this is specified to bound to the rounding-parameters which can be set by fesetround(). What I'm concerned about is direct casting to an integer.

like image 255
Bonita Montero Avatar asked Nov 07 '21 17:11

Bonita Montero


Video Answer


1 Answers

In both specs (C17 and C++20), the compile time rounding is implementation defined.

In the C++ spec, this is specified in lex.fcon, which says

If the scaled value is not in the range of representable values for its type, the program is ill-formed. Otherwise, the value of a floating-point-literal is the scaled value if representable, else the larger or smaller representable value nearest the scaled value, chosen in an implementation-defined manner.

The C spec has similar language (quote taken from N2176, C17 final draft):

the result is either the nearest representable value, or the larger or smaller representable value immediately adjacent to the nearest representable value, chosen in an implementation-defined manner.

It also recommends that translation time conversion should match execution time conversion by library functions (like strtod) but it is not required. See the description of representable values.

Conversions of floating point values to integers are specified in both to truncate (round towards 0 by discarding the fractional part).

like image 147
1201ProgramAlarm Avatar answered Nov 14 '22 23:11

1201ProgramAlarm