Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: Convert Double to Int

I want to compute "which power of a number do I have to use" from a fixed base, e.g. 2.

I want to find the next (integer) power of a number, e.g. 2 ^ 3 = 8 ==> get2Power 8 ==> 3.

This is simple, but get2Power 10 ==> 4 since 2^3=8 as the lower bound and 2^4=16 as the upper bound I want to return the upper one, 4.

With simple math I know that I can calculate the power with some logarithm function, i.e. log(x) / log(2) which results in a Double. But I want to have the next Integer.

My approach looks like

get2Power :: Integer -> Integer
get2Power x 
  | x <= 0 = -1
  | otherwise = round (log(x) / log (2))     

which fails cause there is missing some conversion between the Types. The error message is not helpful to get an idea of what I'm missing.

Could anybody give me a helping hand about how to transform the Double result into an Integer/int?

like image 358
LeO Avatar asked Nov 27 '22 07:11

LeO


1 Answers

To people that lands at this page snared by its title "Convert Double to Int". There are three functions in the Haskell Prelude that help: round, floor and ceiling.

Here is an example:

Prelude> let myFloat = 3.1415 :: Double
Prelude> let y = round myFloat :: Int
Prelude> y
3
Prelude> :type y
y :: Int
like image 97
dsign Avatar answered Dec 05 '22 03:12

dsign