Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
-- 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
You can’t perform that action at this time.