dragonfly02
dragonfly02

Reputation: 3669

How does c# compiler handle addition and multiplication differently

Since float/double numbers in c# can only be represented precisely if they are expressible in base 2; I would expect both t2 and t3 are non-zero but t2 = 0 while t3 is indeed not zero. Can someone explain?

double d2 = 1.0/3.0;
double t2 = 1.0 - 3.0*d2;
double t3 = 1.0 - d2 - d2 - d2;

Upvotes: 3

Views: 117

Answers (2)

xkothe
xkothe

Reputation: 674

I think the problem is not the C# it self, but the way microprocessors work. You cant divide 1/3 and expect a number to be stored as 1/3.

The computer also do some tricks (add error) to make sense of common math:

double d1 = 1/3.0;
d1 = d1 * 3.0;

will result in

 d1 = 1.0

Upvotes: 0

Servy
Servy

Reputation: 203835

In the case of t2 you create several intermediate values that do indeed result in some amount of error. It just so happens that the operations result in equal and opposite amounts of error, resulting in those errors coincidentally cancelling out to a net error of zero, and creating the correct result.

The case of t3 results in the error of each of the intermediate operations being equal and not opposite, resulting in the errors compounding each other, rather than cancelling each other out, resulting in a net non-zero error.

Upvotes: 4

Related Questions