为什么我的立方根算法是错误的? SICP 练习 1.8

Why is my cubic root algorithm wrong? Exercise 1.8 in SICP

> 已修复,

it was not a huge number but a fraction of two huge numbers, so I got a false alarm. The algorithm was right; modifying the last input parameter now the interpreter retrieves it as a decimal comma, and looks like the small number it always was.

我正在做 SICP 的练习 1.8 和 Scheme 的解释器 ̵f̵̵r̵̵e̵̵e̵̵z̵̵e̵s̵ returns 当我评估我的算法时错误的答案。有人知道为什么吗?

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)+(2*y))/3. Use this formula to implement a cube-root procedure analogous to the square-root procedure.

(define (cubert x)
        (cubert-iter x x 1))

(define (cubert-iter x previous guess)
        (if (good-enough previous guess)
             guess
             (cubert-iter x guess (improve x guess))))

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

(define (good-enough previous guess)
        (< (/ (max (square previous)
                   (square guess))
              (min (square previous)
                   (square guess)))
           tolerance))

(define tolerance 2)        

(cubert 1000) ̴f̴̴r̴̴e̴̴e̴̴z̴̴e̴s̴给出了一个巨大的100位数字 (cubert 27) returns 类似于 3049534534593845092305345 可能是评价顺序错误,我看不到

在大多数具有精确固定编号的实现中,方案将在整个执行过程中尝试保持这些数字精确。如果你要对永远无法有精确浮点数的东西进行除法,比如 1 除以 3:

(/ 1 3)
; ==> 1/3

您得到了准确的值 1/3(cubert 27) 的结果完全是 fixnum 操作,所以它也会产生分数结果:

(cubert 27)
; ==> 3 5164693972157389706641814378288819200000000/10804364367444398305386468912180491314165089

如果你想要一个不太精确的数字,比如浮点数,你可以通过从一个不精确的值开始来强制它,或者你可以在之后用 exact->inexact 转换精确的结果:

(cubert #i27)                ; ==> 3.48
(exact->inexact (cubert 27)) ; ==> 3.48

您也可以通过使用不精确 2 在您的算法中强制使用它,即。 #i2 或 `2.02,当你乘法时。这将导致不准确的结果。