From 21bf5448a581e4839c81c4c37e655c0e85e5208a Mon Sep 17 00:00:00 2001 From: bnewbold Date: Mon, 25 Apr 2016 23:53:34 -0400 Subject: tests: sqrt example from SICP --- test/square-root.scm | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 test/square-root.scm (limited to 'test') 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 -- cgit v1.2.3