Created
January 30, 2015 19:01
-
-
Save Kornel/2546388aaac29cdc598e to your computer and use it in GitHub Desktop.
Square root calculated using the Newton - Raphson method in Haskell
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
module NewtonRaphson.Sqrt (nrSqrt) where | |
nrSqrt :: Double -> Double | |
nrSqrt n = within 0.001 (approximations init n) | |
where init = n / 2 | |
approximations :: Double -> Double -> [Double] | |
approximations x0 n = iterate (next n) x0 | |
next :: Double -> Double -> Double | |
next n x0 = (x0 + n / x0) / 2 | |
within :: Double -> [Double] -> Double | |
within eps (x0:t@(x1:xs)) = if abs(x0 - x1) < eps then x1 else within eps t |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment