Problem when computing the power of huge numbers
Diego Alexander Rojas <[email protected]> Wed, 22 Dec 2010 08:14:56 +0100
| Newsgroups | gmane.lisp.scheme.scheme48 |
|---|---|
| Message-ID | <[email protected]> |
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?