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?
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?
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.
The semantics of physical equality (==) is:
x == y
is true implies compare x y
is 0 (which usualy means x = y)x == y
is true if and only if, mutating x will also affect yThat'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)