Jonathon Hewitt
Jonathon Hewitt

Reputation: 23

MIT Scheme Int VS Float

I've been working through SICP using mit-scheme to test the exercises. For Exercise 1.8 you are tasked to write a cube-root function analogous to the given square-root function. My solution for that is below; however, I noticed that in the cube-root function, where the first call to cube-iter is made. If the first argument is 1, the function returns some very large integer, where if it is 1.0 it will return the expected result using mit-scheme. Using the scm interpreter there is no difference between the output when using 1 and 1.0. I was under the impression that there should be no difference between the two.

Code:

(define (cube-root x)
  (cube-iter 1 x))

(define (cube-iter guess x)
  (if (good-enough? guess x)
      guess
      (cube-iter (improve guess x) x)))

(define (good-enough? guess x)
  (< (abs ( - x (cube guess))) .001))

(define (improve guess x)
  (/ (+ (/ x (* guess guess)) (* 2 guess))
   3)))

(define (cube x) (* x x x))

Output for (cube-iter 1 x)) version in mit-scheme: 1592506......

Output for (cube-iter 1.0 x)) version in mit-scheme: 3.0000005410641766

Output for (cube-iter 1 x)) version in SCM: 3.0000005410641766

Output for (cube-iter 1.0 x)) version in SCM: 3.0000005410641766

The version for mit-scheme is 9.2

Upvotes: 0

Views: 267

Answers (1)

Sylwester
Sylwester

Reputation: 48765

It's not a large integer, it is a large exact raio like 1/2 that is damn close to 3 and more accurate than 3.0000005410641766. Look more closely and you'll see the the / between the nominator and denominator.

By using exact numbers a scheme implementation that has support for the full numeric tower would never reduce the exactness for the most common mathematic operations unless it's inheritly inexact, like log. By using one inexact value like 1.0 and all results are inexact since 1 is 1 while 1.0 is in the range around 1.

Since you are approximating cube root I guess 1.0 is the correct value to use since the result is just good enough so returning exact numbers here is not being truthful. If you were doing something else where the result were exact returning a ratio is the correct thing to do and those who don't want a exact result can either use the procedure exact->inexact or pass at least one inexact value to get an inexact value back .

Upvotes: 2

Related Questions