Skip to content

Instantly share code, notes, and snippets.

@wyager
Created December 18, 2015 21:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wyager/33dcc26d1e867c462808 to your computer and use it in GitHub Desktop.
Save wyager/33dcc26d1e867c462808 to your computer and use it in GitHub Desktop.
Getting lots of digits of constants
import Prelude hiding (pi)
import Data.Ratio ((%))
import Data.List(findIndex, splitAt)
-- Thanks to augustss on stackoverflow
showRational :: Int -> Rational -> String
showRational n r =
let d = round (abs r * 10^n)
s = show (d :: Integer)
s' = replicate (n - length s + 1) '0' ++ s
(h, f) = splitAt (length s' - n) s'
in (if r < 0 then "-" else "") ++ h ++ "." ++ f
approx = showRational 1000
pi :: Rational
pi = 2 * pi' 5000 1 3
pi' :: Integer -> Integer -> Integer -> Rational
pi' 0 _ _ = 0
pi' n a b = 1 + (a % b) * (pi' (n-1) (a+1) (b+2))
fac n = product [1..n]
e :: Rational
e = sum [1 % fac n | n <- [0..1000]]
main = print (approx pi) >> print (approx e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment