Reputation: 28
Concerning the library fenv.h in C, I have some difficulties to understand what the rounding direction mode does when using fesetround() and the direction FE_TONEAREST (default) in particular.
There are 4 types of rounding directions in the library :
On doubles :
double res = 0.14*50;
printf ("res = %.50lf \n",res);
This returns : res = 7.00000000000000088817841970012523233890533447265625
(the compiler says that res > 7)
However, on floats :
float res = 0.14*50;
printf ("res = %.50f \n",res);
returns 7.00000000000000000000000000000000000000000000000000
(res = 7)
On long doubles :
long double a;
long double b;
scanf("%Lf",&a);
scanf("%Lf",&b);
long double res = a*b;
printf("%.50Lf \n",res);
returns 7.00000000000000000000000000000000000000000000000000
(res = 7)
Is the double type more risky for floating point arithmetics on the FE_TONEAREST mode ?
Upvotes: 0
Views: 114
Reputation: 80276
Your question has nothing to do with the round-to-nearest rounding mode, which is the default mode anyway. The answer to your question is that 0.14f
is different from 0.14
is different from 0.14L
and none of them is equal to the mathematical ratio of 14 / 100. These (different) numbers 0.14f
, 0.14
and 0.14L
behave differently when multiplied by 50.
The rounding mode affects the behavior of the multiplication, not the value of 0.14f
, 0.14
and 0.14L
(*). The reason why 0.14 * 50 > 7
relates as much to the value of 0.14
than it does to the behavior of *
. Therefore, do not assume that the rounding mode in which *
is executed alone explains what you see.
Is the double type more risky for floating point arithmetics on the FE_TONEAREST mode ?
No, absolutely not.
Note that your float
experiment should be float res = 0.14f*50;
in order to be meaningful. Otherwise, you are multiplying a double-precision constant 0.14
and then rounding the result to float. It is normal for this operation to produce the mathematical result more often than multiplying a single-precision decimal constant does, but again this has nothing to do with the rounding mode and everything to do with the actual operand of the multiplication.
(*) C99 6.4.4.2:5 Floating constants are converted to internal format as if at translation-time.
Upvotes: 4