Skip to content

Instantly share code, notes, and snippets.

@rm-hull
Last active August 29, 2015 14:06
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 rm-hull/89f92e408c66179914a2 to your computer and use it in GitHub Desktop.
Save rm-hull/89f92e408c66179914a2 to your computer and use it in GitHub Desktop.
Newtons method (also know as the Newton-Raphson method) is a textbook example of an iterated method for finding successively better approximations to the roots (or zeroes) of a real-valued function. This program calculates the square root using anonymous recursion by way of the _fixpoint combinator_ (a.k.a. Haskell Curry's paradoxical _Y-combina…
(ns fixpoint.newtons-method)
(defn square [x]
(* x x))
(defn average [x y]
(/ (+ x y) 2))
(defn improve [guess x]
(average guess (/ x guess)))
(defn good-enough? [guess x]
(< (Math/abs (- (square guess) x)) 0.0000001))
(defn fix [r] ; fix point combinator
((fn [f] (f f))
(fn [f]
(r (fn [x] ((f f) x))))))
(defn sqrt [x]
(letfn [(iter [func]
(fn [guess]
(if (good-enough? guess x)
guess
(func (improve guess x)))))]
((fix iter) 1.0)))
(doseq [x (range 1 10)]
(println (str "√" x " = " (sqrt x))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment