Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to round a number in ocaml?

I want if it is bigger or equal to 0 to round it to the bigger number and if it is smaller than 0 to round it to the number before. Eg: If the number is 2.5 show 3 and if the number is -2.5 show -3. How should i write this? I wrote :

let round x = if (x >= 0) then int_of_float x
  else int_of_float ( x -. 1.0);;

or

let round x = if ( x>=0) then truncate (x +. 0.5) 
  else truncate ( x -. 0.5);;

and to both it gives me the same error :

Error: This expression has type int but an expression was expected of type
         float

How should I write it?

like image 265
Jeremy Avatar asked Mar 14 '23 12:03

Jeremy


2 Answers

The compiler is complaining because 0 is a constant of type int. It will work better if you use 0.0.

Personally I use this definition:

let frnd f = floor (f +. 0.5)

However, it doesn't work exactly like you want:

# frnd 2.5;;
- : float = 3.
# frnd (-2.5);;
- : float = -2.
# frnd (-2.500000001);;
- : float = -3.

I.e., it rounds up (toward positive infinity) values halfway between integers.

like image 51
Jeffrey Scofield Avatar answered Mar 17 '23 06:03

Jeffrey Scofield


Since 4.08.0, round is defined in the Float module

# Float.round 2.5
- : float = 3.
# Float.round 2.4
- : float = 2.
like image 27
Keyi Wang Avatar answered Mar 17 '23 06:03

Keyi Wang