Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OCaml floats boxed or un-boxed?

I know that floating point numbers are normally boxed in OCaml, but my difficulty is that word: normally. When are they not boxed? And, if they aren't boxed, how are they represented so the runtime recognizes them as different from ints or pointers?

I've found http://caml.inria.fr/pub/old_caml_site/ocaml/numerical.html, which lists certain times when floats aren't boxed, but it's 11 years old so I don't know if it's still up-to-date, and it doesn't explain HOW they're represented when not boxed.

I'm new to OCaml, so sorry if this is a dumb noob question. Thanks!

like image 350
Zane Beckwith Avatar asked Sep 23 '13 16:09

Zane Beckwith


2 Answers

Floats are unboxed when in an array and when in a record all of whose fields are float. There is a special tag for these cases that marks the collection as containing unboxed floats.

This is described in Section 19.3 of the OCaml manual.

like image 199
Jeffrey Scofield Avatar answered Nov 04 '22 08:11

Jeffrey Scofield


Floats are unboxed in two kinds of situation:

  • When there are only floats in an array (even in polymorphic functions), or in a record (this time, only when all fields are determined as floats at compile time)

  • During sequences of float operations: the compiler will notice that it is not useful to box a float just before unboxing it for the next operation using it, so the float remains unboxed. In:

    let x = 
      let y = a +. b in
      y *. c
    

    The value y is not going to be boxed. This optimization is also done on int32, int64 and nativeint, so that they have actually very good performances in heavy computations.

like image 4
Fabrice Le Fessant Avatar answered Nov 04 '22 08:11

Fabrice Le Fessant