Skip to content

Instantly share code, notes, and snippets.

@frasertweedale
Last active March 2, 2019 14:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frasertweedale/7616e535008ae00e4ffdde587c6bffa9 to your computer and use it in GitHub Desktop.
Save frasertweedale/7616e535008ae00e4ffdde587c6bffa9 to your computer and use it in GitHub Desktop.
Newton's method (Haskell)
{-# LANGUAGE RankNTypes #-}
import Numeric.Natural (Natural)
import Numeric.AD (diff)
newtonRoot
:: (Floating a, Ord a)
=> Natural -- ^ iterations
-> a -- ^ epsilon
-> a -- ^ starting guess
-> (forall b. Floating b => b -> b)
-> Maybe a
newtonRoot i ep x f
| i == 0 = Nothing
| abs (f x) - abs ep < 0 = Just x
| otherwise = newtonRoot (i - 1) ep (x - f x / diff f x) f
main = do
print $ newtonRoot 100 0.01 2 sin
print $ newtonRoot 100 0.01 10 (\x -> x**2 - 612)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment