If I have the following code (this was written in .NET)
double i = 0.1 + 0.1 + 0.1;
Why doesn't i equal 0.3?
Any ideas?
-
This is not specific to .NET by the way, Float and Double based in binary have this problem for many decimal values converted to binary.Jared Updike– Jared Updike2008年10月23日 07:20:17 +00:00Commented Oct 23, 2008 at 7:20
7 Answers 7
You need to read up on floating point numbers. Many decimal numbers don't have an exact representation in binary so they won't be an exact match.
That's why in comparisons, you tend to see:
if (abs(a-b) < epsilon) { ...
where epsilon is a small value such as 0.00000001, depending on the accuracy required.
Comments
Double is a 64-bit floating point data type. It stores decimals as approximate values. If you need exact values, use the Decimal data type which is a Binary Coded Decimal data type.
1 Comment
The precision of floating point arithmetic cannot be guaranteed.
1 Comment
Equality with floating point numbers is often not used because there is always an issue with the representation. Normally we compare the difference between two floats and if it is smaller than a certain value (for example 0.0000001) it is considdered equal.
Comments
Double calculation is not exact. You have two solution:
- Use the
Decimaltype which is exact - compare abs(i - 0.3) < espilon
4 Comments
decimal is not "exact", but it is much more what-you-see-is-what-you-get than double is, because what you usually look at is the string representation of the number, and for decimal it is almost obvious what the underlying "internal" value is, given the string representation. I invite you to look at these decimal expressions (using C# syntax here): 25d / 3d and (25d / 3d) * 3d and 22d / 3d and (22d / 3d) * 3d.Comments
Have a look at this thread:
Why do I see a double variable initialized to some value like 21.4 as 21.399999618530273?