Created
November 20, 2011 00:58
-
-
Save undetected1/1379632 to your computer and use it in GitHub Desktop.
Sqrt by Newton's method.
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
;; Oh yeah. | |
;; | |
;;; Code: | |
(defun (sqrt-iter guess x) | |
(if (good-enough? guess x) | |
guess | |
(sqrt-iter (improve guess x) | |
x))) | |
(defun (improve guess x) | |
(average guess (/ x guess))) | |
(defun (average x y) | |
(/ (+ x y) 2)) | |
(defun (good-enough? guess x) | |
(< (abs (- (square guess) x)) 0.001)) | |
(defun (sqrt x) | |
(sqrt-iter 1.0 x)) | |
;; Running Baby! | |
(sqrt 9) | |
(sqrt (+ 100 37)) | |
(sqrt (+ (sqrt 2) (sqrt 3))) | |
(square (sqrt 1000)) |
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
import static java.lang.Math.*; | |
import static java.lang.System.out; | |
public class SqrtDemo { | |
public static void main(String... args) { | |
out.printf("%.15f\n", sqrt (9)); | |
out.printf("%.15f\n", sqrt (100 + 37)); | |
out.printf("%.15f\n", sqrt (sqrt (2) + sqrt (3))); | |
out.printf("%.15f\n", pow (sqrt (1000), 2)); | |
} | |
private static double sqrt_iter(double guess, double x) { | |
if (good_enough (guess, x)) return guess; | |
return sqrt_iter (improve (guess, x), x); | |
} | |
private static double improve(double guess, double x) { | |
return average(guess, (x / guess)); | |
} | |
private static double average(double x, double y) { | |
return (x + y) / 2; | |
} | |
private static boolean good_enough(double guess, double x) { | |
return (abs (pow (guess, 2.0) - x) < 0.001) ? true : false; | |
} | |
private static double sqrt(double x) { | |
return sqrt_iter(1.0, x); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment