Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is double Multiplication Broken in .NET? [duplicate]

Tags:

c#

.net

math

If I execute the following expression in C#:

double i = 10*0.69; 

i is: 6.8999999999999995. Why?

I understand numbers such as 1/3 can be hard to represent in binary as it has infinite recurring decimal places but this is not the case for 0.69. And 0.69 can easily be represented in binary, one binary number for 69 and another to denote the position of the decimal place.

How do I work around this? Use the decimal type?

like image 438
Dan Avatar asked Sep 14 '09 10:09

Dan


2 Answers

Because you've misunderstood floating point arithmetic and how data is stored.

In fact, your code isn't actually performing any arithmetic at execution time in this particular case - the compiler will have done it, then saved a constant in the generated executable. However, it can't store an exact value of 6.9, because that value cannot be precisely represented in floating point point format, just like 1/3 can't be precisely stored in a finite decimal representation.

See if this article helps you.

like image 128
Jon Skeet Avatar answered Sep 18 '22 15:09

Jon Skeet


why doesn't the framework work around this and hide this problem from me and give me the right answer,0.69!!!

Stop behaving like a dilbert manager, and accept that computers, though cool and awesome, have limits. In your specific case, it doesn't just "hide" the problem, because you have specifically told it not to. The language (the computer) provides alternatives to the format, that you didn't choose. You chose double, which has certain advantages over decimal, and certain downsides. Now, knowing the answer, you're upset that the downsides don't magically disappear.

As a programmer, you are responsible for hiding this downside from managers, and there are many ways to do that. However, the makers of C# have a responsibility to make floating point work correctly, and correct floating point will occasionally result in incorrect math.

So will every other number storage method, as we do not have infinite bits. Our job as programmers is to work with limited resources to make cool things happen. They got you 90% of the way there, just get the torch home.

like image 35
Russell Steen Avatar answered Sep 19 '22 15:09

Russell Steen