2

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?

4

7 回答 7

6

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.

于 2008-10-23T07:10:34.350 回答
3

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.

于 2008-10-23T07:10:56.000 回答
1

The precision of floating point arithmetic cannot be guaranteed.

于 2008-10-23T07:09:39.263 回答
1

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.

于 2008-10-23T07:11:08.763 回答
1

Double calculation is not exact. You have two solution:

  • Use the Decimal type which is exact
  • compare abs(i - 0.3) < espilon
于 2008-10-23T07:11:34.860 回答
1

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

于 2008-10-23T07:18:35.377 回答
0

Have a look at this thread:

Why do I see a double variable initialized to some value like 21.4 as 21.399999618530273?

于 2008-10-23T07:25:04.617 回答