Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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)
(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
You can’t perform that action at this time.