Created
December 18, 2015 21:27
-
-
Save wyager/33dcc26d1e867c462808 to your computer and use it in GitHub Desktop.
Getting lots of digits of constants
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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