Skip to content

Instantly share code, notes, and snippets.

@dawranliou
Last active May 2, 2018 00:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dawranliou/00cbf1180a1fbc77f6817fd960456be1 to your computer and use it in GitHub Desktop.
Save dawranliou/00cbf1180a1fbc77f6817fd960456be1 to your computer and use it in GitHub Desktop.
(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
@dawranliou
Copy link
Author

Line 1: Define function
Line 2: Function arguments. From left to right are:

  • f - Function
  • fprime - The derivative function of f
  • tol - The tolerance
  • max-iteration - Maximum number to iterations
  • x - The initial position of x

Line 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 updated x-new and decremented max-iteration.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment