Cookbook/Numbers
From HaskellWiki
< Cookbook(Difference between revisions)
(→Rounding numbers) 

Line 16:  Line 16:  
</haskell> 
</haskell> 

 
 

−   getting the least number not less than <code>x</code> 
+   find the nearest integer greaterthan or equal to <code>x</code> 
 [http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v%3Aceiling ceiling] 
 [http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v%3Aceiling ceiling] 

<haskell> 
<haskell> 

Line 22:  Line 22:  
</haskell> 
</haskell> 

 
 

−   getting the greatest number not greater than <code>x</code> 
+   find the nearest integer less than or equal to <code>x</code> 
 [http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v%3Afloor floor] 
 [http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v%3Afloor floor] 

<haskell> 
<haskell> 
Revision as of 11:31, 23 April 2009
Numbers in Haskell can be of the typeInt, Integer, Float, Double, or Rational
Contents 
1 Rounding numbers
Problem  Solution  Examples 

rounding  round  round 3.4 > 3 round 3.5 > 4 
find the nearest integer greaterthan or equal to x

ceiling  ceiling 3.1 > 4 
find the nearest integer less than or equal to x

floor  floor 3.5 > 3 
2 Taking logarithms
log 2.718281828459045 > 1.0 logBase 10 10000 > 4.0
3 Generating random numbers
import System.Random main = do gen < getStdGen let ns = randoms gen :: [Int] print $ take 10 ns
4 Binary representation of numbers
import Data.Bits import Data.List (foldl')  Extract a range of bits, mostsignificant first bitRange :: Bits a => a > Int > Int > [Bool] bitRange n lo hi = foldl' (\l > \x > testBit n x : l) [] [lo..hi]  Extract all bits, mostsignificant first bits :: Bits a => a > [Bool] bits n = bitRange n 0 (bitSize n  1)  Display a number in binary, including leading zeroes.  c.f. Numeric.showHex showBits :: Bits a => a > ShowS showBits = showString . map (\b > if b then '1' else '0') . bits
5 Using complex numbers
Problem  Solution  Examples 

creating a complex number from real and imaginary rectangular components  (:+)  import Complex 1.0 :+ 0.0 > 1.0 :+ 0.0 
creating a complex number from polar components  mkPolar  import Complex mkPolar 1.0 pi > (1.0) :+ 1.2246063538223773e16 