Last active
May 2, 2018 00:45
-
-
Save dawranliou/00cbf1180a1fbc77f6817fd960456be1 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
(defn newton | |
[f fprime tol max-iteration x] | |
(if (<= max-iteration 0) | |
nil | |
(let [y (f x) | |
yprime (fprime x) | |
x-new (- x (/ y yprime))] | |
(if (<= (Math/abs(- x-new x)) (* tol (Math/abs x-new))) | |
x-new | |
(newton f fprime tol (dec max-iteration) x-new))))) | |
(newton #(- (* % %) 2) #(* 2 %) 0.00000001 20 100) | |
;;1.4142135623730951 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Line 1: Define function
Line 2: Function arguments. From left to right are:
f
- Functionfprime
- The derivative function off
tol
- The tolerancemax-iteration
- Maximum number to iterationsx
- The initial position of xLine 3 - Safe-guarding the recursive function by checking the max-iteration number. If reached max-iteration, return
nil
.Line 5 - Bind symbols for the current iteration
Line 8 - The condition to determine whether
x-new
is closed enough to the solution.Line 10 - Recursively call
newton
function with updatedx-new
and decrementedmax-iteration
.