Lionel wrote:

Hi all,

I'm facing a strang issue doing calculation on Double values. I read

some thread on the newsgroups warning about type translations (eg

Single to Double), but here I'm doing no conversion at all.

The issue I'm facing looks so basic but I'm really lost... I'm doing

all my calculations in Double, and the results are not correct. Did I

miss something?

double a, b;

a = 4.5d;

b = a + 0.10d;

Console.WriteLine(ee == 4.6d); // returns true

Lucky.

b = a + 0.20d;

Console.WriteLine(ee == 4.7d); // returns true

Lucky again!

b = a + 0.10d + 0.10d;

Console.WriteLine(ee == 4.7d); // returns false !!!

Not surprising.

b = a + 0.30d;

Console.WriteLine(ee == 4.8d); // returns true

b = a + 0.10d + 0.10d + 0.10d;

Console.WriteLine(ee == 4.8d); // same: returns false

Many thanks in advance for your help,

Short answer: Don't use floating point types for exact calculation. In

particular, don't ever use == with floating point types.

Slightly longer answer: If you are using quantities best represented by

floating point types (and numbers such as 0.1, 4.6, are not), and you

want to compare equality, decide on some small epsilon which for your

application can mean 'close enough'; and then say two floating point

quantites are equal if they are within epsilon of each other. eg:

static const double epsilon = 0.0001d;

static bool CloseEnough(double d1, double d2)

{

return (Math.Abs(d1 - d2) < epsilon);

}

Here's the C# for my favorite example for why floating point is

inappropriate for exact quantities:

Console.WriteLine((0.1d + 0.1d + 0.1d - 0.3d));

Try it! (First guess what you think the output will be of course...)

Long answer: Go look up floating point at wikipedia or somewhere :)

--

Larry Lard

Replies to group please