views:

194

answers:

7
+2  Q: 

double in .net

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?

+1  A: 

The precision of floating point arithmetic cannot be guaranteed.

Andrew
It can and is guaranteed in many systems - but it's guaranteeing a certain level of precision rather than perfection (which is unattainable here, as neither 0.1 nor 0.3 can be exactly represented in binary floating point).
Jon Skeet
+6  A: 

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.

paxdiablo
+3  A: 

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.

Darksider
Some fractional values are not approximate in binary (like 1/2, or 1/4 or 3/4), just many numbers in base ten (like 0.1, 0.3) get approximated when converted to base two.
Jared Updike
+1  A: 

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.

Gamecat
+1  A: 

Double calculation is not exact. You have two solution:

  • Use the Decimal type which is exact
  • compare abs(i - 0.3) < espilon
Nico
Decimal is not "exact" - it just has a different representation, that happens to work better with typical decimal values - i.e. base-10 rounding. That doesn't make it "exact".
Marc Gravell
+1 to Marc's comment :)
Jon Skeet
Having never used .NET, in what sense is Decimal not exact? Do you mean such things as sqrt(2) and pi or are there actually decimal values (I mean any base-10 number with finite number of digits) that can't be represented by it?
paxdiablo
Doing arithmetic on things with different scales (i.e. add a very large number and a very small number) would be a trivial example - but just things like "divide by 3" then "multiply by 3" should be enough to not count as "exact".
Marc Gravell
+1  A: 

Jon Skeet has a very good walkthrough of this here, and the same for decimal here.

Marc Gravell