Search code examples
phpjavascriptprogramming-languages

Why doesn't this comparison work?


Possible Duplicate:
Is JavaScript's Math broken?

If(0.3-0.2==0.2-0.1) most of programming language showing result false.So I want to know which Language Support this statement true and why most of language shows false.

Tested in Javascript and PHP. Why does this happen?


Solution

  • The reason that this happens is not to do necessarily with a language, per se, but an implementation. The answer to this question is that when you write If(0.3-0.2==0.2-0.1), you are thinking that the operations performed are in the rationals, this is false, they are indeed in floating point arithmetic. Indeed, within floating point arithmetic, this is false! So the answer is: any language which defaults to interpreting constants in an arbitrarily precise arithmetic. (For example, if these had been written in Haskell using a Rational number, then the test would have "worked.") For completeness: the Racket language does this.