Skip to content

Instantly share code, notes, and snippets.

@umairsd
Created September 30, 2015 16:23
Show Gist options
  • Select an option

  • Save umairsd/8055010b79409cc614be to your computer and use it in GitHub Desktop.

Select an option

Save umairsd/8055010b79409cc614be to your computer and use it in GitHub Desktop.
-- 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