0

Possible Duplicate:
Why is floating point arithmetic in C# imprecise?

Console.WriteLine(0.5f * 2f);       // 1
Console.WriteLine(0.5f * 2f - 1f);  // 0

Console.WriteLine(0.1f * 10f);      // 1
Console.WriteLine(0.1f * 10f - 1f); // 1.490116E-08

Why does 0.1f * 10f - 1f end up being 1.490116E-08 (0.0000001490116)?

Community
  • 1
  • 1
Homam
  • 23,263
  • 32
  • 111
  • 187
  • 5
    See: ["Why can't decimal numbers be represented exactly in binary?"](http://stackoverflow.com/questions/1089018/why-cant-decimal-numbers-be-represented-exactly-in-binary) – John Kugelman Nov 25 '10 at 00:41
  • See [Why is floating point arithmetic in C# imprecise? ](http://stackoverflow.com/questions/753948/why-is-floating-point-arithmetic-in-c-imprecise). – Matthew Flaschen Nov 25 '10 at 00:42
  • I can't post an answer due to the duplicate flag, but the cause is actually C#'s use of intermediate precision. See http://stackoverflow.com/a/30280829/392585 – Simon Byrne Oct 23 '15 at 20:58

6 Answers6

4

See Wiki: Floating Point. float/double/decimal are relative precision types. Not all values (of which there are infinitely many) can be exactly stored. You are seeing the result of this loss of accuracy. This is why it is almost always correct to use |a - b| < small_delta for float-point comparisons.

1

Because floating operations are not precise, take a look here:

section Some other computer representations for non-integral numbers. 0.1 cannot finitely be represented in base 2.

icyrock.com
  • 27,952
  • 4
  • 66
  • 85
1

Take a look at What Every Computer Scientist Should Know About Floating-Point Arithmetic.

Daniel Pryden
  • 59,486
  • 16
  • 97
  • 135
1

Read this (explains quite exactly this case): http://www.exploringbinary.com/the-answer-is-one-unless-you-use-floating-point/

Lucero
  • 59,176
  • 9
  • 122
  • 152
0

Easy, approximations accumulate.

Blindy
  • 65,249
  • 10
  • 91
  • 131
0

0.5 is representable exactly in floating point, which is why 0.5*2 = 1 exactly.

However, 0.1 is not representable exactly, hence 0.1*10 is not exactly 1.

lijie
  • 4,811
  • 22
  • 26