K
Klaus Bonadt
I have found strange behaviour in casting floating point values in C++ 6.0
to int:
If I enter in the watch window while debugging in version 6.0 the following
term:
(1.4 - 1.0) * 10.0
the result will be 4.0 - as expected.
But if I cast the same to int:
(int)((1.4 - 1.0) * 10.0)
the result will be 3!
I tried the same with C# in .NET:
(1.4 - 1.0) * 10.0
will be evaluated differently, sometimes 4.019999999991, sometimes
3.9999999999999991.
In according to the different values for the floating point calculation, the
cast to int:
(int)((1.4 - 1.0) * 10.0)
will yield into results 3 or 4, respectively.
Using floor and ceil or Math.Floor and Math.Ceiling does not change
anything, because the faulty evaluation will be done at first.
OK, I understand that floating point calculation must have limited
preciseness. However, I am surprised that this simple term is evaluated
wrongly.
How to overcome this in daily practice?
Never go back from double to int?
Using other rounding algorithm?
What do you do?
Regards,
Klaus
to int:
If I enter in the watch window while debugging in version 6.0 the following
term:
(1.4 - 1.0) * 10.0
the result will be 4.0 - as expected.
But if I cast the same to int:
(int)((1.4 - 1.0) * 10.0)
the result will be 3!
I tried the same with C# in .NET:
(1.4 - 1.0) * 10.0
will be evaluated differently, sometimes 4.019999999991, sometimes
3.9999999999999991.
In according to the different values for the floating point calculation, the
cast to int:
(int)((1.4 - 1.0) * 10.0)
will yield into results 3 or 4, respectively.
Using floor and ceil or Math.Floor and Math.Ceiling does not change
anything, because the faulty evaluation will be done at first.
OK, I understand that floating point calculation must have limited
preciseness. However, I am surprised that this simple term is evaluated
wrongly.
How to overcome this in daily practice?
Never go back from double to int?
Using other rounding algorithm?
What do you do?
Regards,
Klaus