Last active
December 9, 2015 23:59
-
-
Save dyba/4348171 to your computer and use it in GitHub Desktop.
SICP 1.7 Solution
This file contains 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
(define (good-enough? guess next-guess) | |
(< (/ (abs (- guess next-guess)) guess) 0.001)) | |
(define (average x y) | |
(/ (+ x y) 2)) | |
(define (improve guess x) | |
(average guess (/ x guess))) | |
(define (sqrt-iter guess x) | |
(if (good-enough? guess (improve guess x)) | |
guess | |
(sqrt-iter (improve guess x) | |
x))) |
This file contains 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
' Just for kicks | |
Function Average(X As Double, Y As Double) As Double | |
Average = (X + Y) / 2 | |
End Function | |
Function Improve(Guess As Double, NextGuess As Double) As Double | |
Improve = Average(Guess, X / Guess) | |
End Function | |
Function IsGoodEnough(Guess As Double, NextGuess As Double) As Boolean | |
IsGoodEnough = (Abs(Guess - NextGuess) / Guess) < 0.001 | |
End Function | |
Function SqrtIter(Guess As Double, X As Double) As Double | |
If (IsGoodEnough(Guess, Improve(Guess, X))) Then | |
SqrtIter = Guess | |
Else | |
SqrtIter = SqrtIter(Improve(Guess, X), X) | |
End If | |
End Function |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment