November 23, 2008

at Sunday, November 23, 2008 Labels: , , Posted by Billy

Exercise 1.3
Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers.


(defun square (x) (* x x))

(defun sum-of-squares (lst)
(apply #'+ (mapcar #'square lst)))

(defun get-largest-2 (lst)
(when (>= (length lst) 2)
(let ((sorted-lst (sort lst #'>)))
(list (first sorted-lst)
(second sorted-lst)))))

;;; This does better and takes any number of arguments
(defun sum-sqr-lrgst (lst)
(sum-of-squares (get-largest-2 lst)))


Exercise 1.8
Newton's method for cube roots is based on the fact that if y is an approximation to the cube root of x, then a better approximation is given by the value
(x/y^2 + 2y)/3
Use this formula to implement a cube-root procedure analogous to the square-root procedure.


(defconstant +tolerance+ 0.001)

(defun cube (x) (* x x x))

(defun good-enough-p (guess x)
"Returns true if the cube of the guess differs from x by less
than the tolerance"
(< (abs (- (cube guess) x)) +tolerance+))

(defun improve (guess x)
"Returns a better approximation of the cube root of x"
(/ (+ (/ x
(square guess))
(* 2 guess))
3))

(defun cube-rt-iter (guess x)
(if (good-enough-p guess x)
guess
(cube-rt-iter (improve guess x) x)))

(defun cube-rt (x)
"Calculates the cube root of x"
(cube-rt-iter 1.0 x))

0 comments: