aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorbnewbold <bnewbold@robocracy.org>2016-04-25 23:53:34 -0400
committerbnewbold <bnewbold@robocracy.org>2016-04-25 23:53:34 -0400
commit21bf5448a581e4839c81c4c37e655c0e85e5208a (patch)
treea401c5f5ef828a256a2a5e92bd8f488eea6da8e0
parent5bf77cc39f3ce9d9be06ebcc12f6d587c4ae1847 (diff)
downloadspectrum-21bf5448a581e4839c81c4c37e655c0e85e5208a.zip
spectrum-21bf5448a581e4839c81c4c37e655c0e85e5208a.tar.gz
tests: sqrt example from SICP
-rw-r--r--test/square-root.scm37
1 files changed, 37 insertions, 0 deletions
diff --git a/test/square-root.scm b/test/square-root.scm
new file mode 100644
index 0000000..4c2c1cf
--- /dev/null
+++ b/test/square-root.scm
@@ -0,0 +1,37 @@
+; see: https://mitpress.mit.edu/sicp/chapter1/node9.html
+
+(define square
+ (lambda (x)
+ (* x x)))
+
+(define average
+ (lambda (x y)
+ (/ (+ x y) 2)))
+
+(define improve
+ (lambda (guess x)
+ (average guess (/ x guess))))
+
+(define good-enough?
+ (lambda (guess x)
+ (< (abs (- x (square guess)))
+ 0.001)))
+
+(define sqrt-iter
+ (lambda (guess x)
+ (if (good-enough? guess x)
+ guess
+ (sqrt-iter (improve guess x) x))))
+
+(define test-sqrt
+ (lambda (x)
+ (sqrt-iter 1.0 x)))
+
+(test-sqrt 9)
+; => 3.00009155413138
+(test-sqrt (+ 100 37))
+; => 11.704699917758145
+(test-sqrt (+ (test-sqrt 2) (test-sqrt 3)))
+; => 1.7739279023207892
+(square (test-sqrt 1000))
+; => 1000.000369924366