Last active
March 2, 2019 14:59
-
-
Save frasertweedale/7616e535008ae00e4ffdde587c6bffa9 to your computer and use it in GitHub Desktop.
Newton's method (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
{-# 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