Orbifx's Logarion
Title:
Int of float hazard in OCaml
Authors:
orbifx
Date:
Topics:
Programming > Ocaml
Id:
c0615a9d-3844-4b56-91cc-4b1968ddd7ab

Watch out when converting from `float` to `int` in OCaml, as there can inconsistent and unintuitive behaviour. OCaml has rarely given me hassle with subtle and obscure issues whilst developing, but this has happened. I don't remember my case, but I can offer some examples from caml-list.

Example was posted on caml-list by `rixed`:

int_of_float (float_of_int max_int) = -4611686018427387904

Examples by Nicolas Ratier:

int_of_float (infinity);; - : int = 0 int_of_float (neg_infinity);; - : int = 0

There was a bug raised about this years ago at <https://caml.inria.fr/mantis/view.php?id=4207>, but it was not deemed a bug. `xleroy` explains how this behaviour was inherited by C.