OCaml's standard library includes several floating-point functions equivalent to C ones, such as mod_float
for C's fmod()
, the exponentiation operator **
for C's pow()
, and other functions such as ceil
, log
, etc.
But does it also include equivalents for round()
and trunc()
? There is truncate
/int_of_float
, but their type is float -> int
and not float -> float
.
It contains the
modf
function, that is a swiss-knife function, with which you can define thetruncatef
androundf
functions:The
round
function also can be expressed withmodf
However it can be expressed more succinctly (and efficiently) with
floor
But both rounding functions are a little bit buggy, as comment in
core
's implementation states:So a little bit more correct way to implement the rounding would be (from Core library):
But even this
round_nearest
is not flawless, for example:This
0.49999999999999994
is an immediate predecessor of0.5
. Pascal's blog contains suggestions on how to solve this issue. The following should work in OCaml:And this is only one rounding policy, round to nearest (the intuitive one). There are other policies, that have their own caveats.