Created
September 30, 2015 16:23
-
-
Save umairsd/8055010b79409cc614be to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| -- Miscellaneous arithmetic functions | |
| -- Square roots using Newton's method | |
| sqrtNewton :: (Floating a, Ord a) => a -> a | |
| sqrtNewton n = head $ dropWhile (\g -> abs(n - g^2) > tolerance) $ iterate (newGuess n) 1 | |
| where | |
| tolerance = 0.000001 | |
| newGuess :: Floating a => a -> a -> a | |
| newGuess n oldGuess = (oldGuess + n / oldGuess) / 2 | |
| -- Integer square root using Newton's method | |
| sqrtNewtonInt :: Integer -> Integer | |
| sqrtNewtonInt n = head $ dropWhile (\g -> g*g > n || (g+1)^2 < n ) $ iterate (newGuessInt n) 1 | |
| newGuessInt :: Integer -> Integer -> Integer | |
| newGuessInt n oldGuess = (oldGuess + n `div` oldGuess) `div` 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment