Skip to content

Instantly share code, notes, and snippets.

@Kornel
Created January 30, 2015 19:01
Show Gist options
  • Save Kornel/2546388aaac29cdc598e to your computer and use it in GitHub Desktop.
Save Kornel/2546388aaac29cdc598e to your computer and use it in GitHub Desktop.
Square root calculated using the Newton - Raphson method in Haskell
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