9

Why does 1 == 1 return true and 1.0 == 1.0 return false?

I think = is structural and == is physical, so shouldn't both return false?

user2864740
  • 60,010
  • 15
  • 145
  • 220
user3340037
  • 731
  • 2
  • 8
  • 23

2 Answers2

14

The problem isn't with the values, the problem is with physical equality ==. Its meaning is implementation-dependent except for certain specific guarantees.

In the usual OCaml implementation, floating values are boxed, so it's normal for no two values of type float to be physically equal.

Conversely, int values are not boxed, so two equal int values will be physically equal.

Physical equality should not be used unless you're very sure you know what you're doing. It violates many desired properties of a functional language, such as referential transparency, as in this case.

Update: the specific guarantees for the meaning of == are given by Pierre Chambart in his excellent answer.

Jeffrey Scofield
  • 65,646
  • 2
  • 72
  • 108
13

The semantics of physical equality (==) is:

  • on any value x == y is true implies compare x y is 0 (which usualy means x = y)
  • on mutable values if x == y is true if and only if, mutating x will also affect y

That's all, do not assumes anything else. (see {http://caml.inria.fr/pub/docs/manual-ocaml-4.02/libref/Pervasives.html#VAL%28==%29}

Note that compare x y = 0 is not exactly equivalent to x = y because nan is not equal to nothing, including itself

(by the way since Ocaml 4.02 an optimisation makes 1.0 == 1.0 true in native code, but not in bytecode)

Pierre Chambart
  • 1,469
  • 12
  • 17