Last active
August 29, 2015 14:06
-
-
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…
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
(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