sicp_examples/chapter_1/ex_7.rkt

34 lines
2 KiB
Racket

#lang sicp
;The good-enough? test used in computing square roots will not be very effective for finding the square roots of very small numbers. Also, in real computers, arithmetic operations are almost always performed with limited precision.
;This makes our test inadequate for very large numbers. Explain these statements, with examples showing how the test fails for small and large numbers. An alternative strategy for implementing good-enough? is to watch
;how guess changes from one iteration to the next and to stop when the change is a very small fraction of the guess. Design a square-root procedure that uses this kind of end test. Does this work befoer for small and large numbers?
;--------------------------------------------------------------------------------------------------------------------------
(define (sqrt x)
(define (square x) (* x x))
(define (good-enough? guess)
(< (abs (- (square guess) x)) 0.001)
)
(define (improve guess)
(/ (+ guess (/ x guess)) 2)
)
(define (sqrt-iter guess)
(if (good-enough? guess)
guess
(sqrt-iter (improve guess))
)
)
(sqrt-iter 1.0)
)
;For the large numbers --> the problem is that we cannot get the number larger than 13 digits
(sqrt 1000000000000) ;the result should be 1000000.0 // we get the result back //the number is not larger than 13 digit
(sqrt 10000000000000) ;nothing happened //the number is more than 14 digit so that nothing happened
;For the small numbers --> inaccurate
(sqrt 0.000001) ;the result should be 0.031260655525445276 //when we check if we square of the result(0.031260655525445276) we should get the result close to 0.000001 but instead we get 0.001059495018662289
(sqrt 0.000123) ;the result should be 0.03254988507909497 //same as explain erlier we should get 0.000123 but we get 0.0009772285838805523
;Thus, these example explain why the test fail for small and large number
;--------------------------------------------------------------
;What can we do?? (An alternative strategy)