Diego Alexander Rojas
2010-12-22 07:14:56 UTC
Hi,
I've been recently following the book Structure and Interpretation of computer
programs and I found something very strange. I currently have this two
functions to compute an exponential function:
(define (even? n)
(= (remainder n 2) 0))
(define (square x) (* x x))
(define (fast-exp b n)
(cond ((= n 0) 1)
((even? n) (square (fast-exp b (/ n 2))))
(else (* b (fast-exp b (- n 1))))))
(define (exp-iter b n sol)
(cond ((= n 0) sol)
((even? n) (exp-iter (square b) (/ n 2) sol))
(else (exp-iter b (- n 1) (* b sol)))))
(define (myfast-exp b n)
(exp-iter b n 1))
both give different results both non are the correct one (I checked
with python,
octave and calc). However this functions just start to fail when computing
very big exponentials, because it didn't fail with numbers such as
123 ^ 331
Any Suggestions?
I've been recently following the book Structure and Interpretation of computer
programs and I found something very strange. I currently have this two
functions to compute an exponential function:
(define (even? n)
(= (remainder n 2) 0))
(define (square x) (* x x))
(define (fast-exp b n)
(cond ((= n 0) 1)
((even? n) (square (fast-exp b (/ n 2))))
(else (* b (fast-exp b (- n 1))))))
(define (exp-iter b n sol)
(cond ((= n 0) sol)
((even? n) (exp-iter (square b) (/ n 2) sol))
(else (exp-iter b (- n 1) (* b sol)))))
(define (myfast-exp b n)
(exp-iter b n 1))
both give different results both non are the correct one (I checked
with python,
octave and calc). However this functions just start to fail when computing
very big exponentials, because it didn't fail with numbers such as
123 ^ 331
Any Suggestions?