.NET and Beyond: Best Practices for Using Double Arithmetic

I am developing a program that does some floating point calculations, and I came across an interesting rounding problem in .NET, according to which the expression:

0.1 + 0.2 == 0.3

evaluates to false because:

0.1 + 0.2

matters 0.30000000000000004, not 0.3. This has a very serious effect on unit testing.

I understand why this happens, but I am interested to know: what are the best practices to follow when working with double arithmetic in order to avoid such problems when possible?

EDIT : using type decimaldoesn't help

SUMMARY : I appreciate all for the comments. Unfortunately, some of you have suggested that this question is how to make 0.1 + 0.2 equal to 0.3, and that is not what I asked for. I accept that floating arithmetic can return a value with a change. I asked what general strategy should be followed so that this variation would not cause problems. I think this issue is ready to close.

+3
source share
3 answers

Usually you check equality to a certain tolerance.

So, in NUnit , for example, you can write:

Assert.AreEqual(x, y, tol);

where tolis the appropriate selected tolerance value. Other structural units of testing will have a similar approval function for floating point values.

, , , . , , , - . .

+5

- .

: #


Decimal - , : decimal a = 0.1M

((0.1M+0.2M)==0.3M) true!

+2

, :

: http://randomascii.wordpress.com/category/floating-point/

[GOLDBERG91]
, , 1991. ", ". ACM Computing Surveys, vol. 23, . 1, 1991 . . 5-48.

0

All Articles