Mihalko
Mihalko

Reputation: 583

math.h default rounding mode not clear

I am facing very strange fact about rounding of float and conversion to int.

As is stated here: http://www.gnu.org/software/libc/manual/html_node/Rounding.html

Rounding to nearest representable value is default rounding mode. But it doesn`t seem to be.

So I have created this simple program:

#include <fenv.h>
#include <stdio.h>

int a;
double b;

main() {
  b=1.3; a=b; printf("%f %d\n",b,a);
  b=1.8; a=b; printf("%f %d\n",b,a);
  b=-1.3; a=b; printf("%f %d\n",b,a);
  b=-1.8; a=b; printf("%f %d\n",b,a);
  printf("%d %d %d\n",fegetround(),FE_TONEAREST,FE_TOWARDZERO);
}

Program was compiled with gcc-4.7 (debian), cygwin gcc and Visual studio. Output was same, only definition of FE_TOWARDZERO changed.

Output of program:

 1.300000 1
 1.800000 1
-1.300000 -1
-1.800000 -1
0 0 3072

So we can clearly see, that rounding mode is set to FE_TONEAREST (default) in all tested compilers, but all of them are rounding towards zero.

Why?

PS: Yes, I can use Math.round() but I am wondering why is this happening.

Upvotes: 1

Views: 2209

Answers (2)

Mihalko
Mihalko

Reputation: 583

Ok, I have found question why is this happening. As is stated here:

http://software.intel.com/en-us/articles/fast-floating-point-to-integer-conversions

in chapter

A Closer Look at Float-to-Int Conversions

The problem with casting from floating-point numbers to 32-bit integers stems from the ANSI C standard, which states the conversion should be effected by truncating the fractional portion of the number and retaining the integer result. Because of this, whenever the Microsoft Visual C++ 6.0 compiler encounters an (int) or a (long) cast, it inserts a call to the _ftol C run-time function. This function modifies the floating-point rounding mode to 'truncate', performs the conversion, and then resets the rounding mode to its original state prior to the cast.

Upvotes: 0

user529758
user529758

Reputation:

Because the rounding mode applies to floating-point rounding functions. Conversion to int always truncates.

Upvotes: 2

Related Questions