Skip to content

Instantly share code, notes, and snippets.

@zbigniewTomczak
Created June 23, 2014 16:17
Show Gist options
  • Save zbigniewTomczak/20428932e810120f7726 to your computer and use it in GitHub Desktop.
Save zbigniewTomczak/20428932e810120f7726 to your computer and use it in GitHub Desktop.
#; Heron's algorithm of calculating a square root
#; https://www.youtube.com/watch?v=XYKRVNQ_MqE
(define (abs x)
(if (< x 0) (- x) x))
(define (average x y)
(/ (+ x y) 2))
(define (improve guess x)
(average guess (/ x guess)))
(define (good-enough? guess x)
(< (abs (- (square guess) x)) .001))
(define (try guess x)
(if (good-enough? guess x)
guess
(try (improve guess x) x)))
(define (sqrt x) (try 1 x))
(sqrt 2)
#; => 1.4142156862745097
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment