0

我正在为我的编程课使用 DrRacket。我认为使用简化的语法。练习是以给定精度计算给定数字的 n 次根。该程序运行良好,但如果尝试将其与 243 的 5 次根(即 3)一起使用,则程序计算速度太慢。但是,如果堆叠该(improve 1 5 243)功能,它就可以工作。但是如果我堆叠它的次数超过 7 次,程序执行时间就会太长。

问题是什么?

这是程序:(它使用牛顿算法)

(check-within (nth-root 3 125 0.001) 5 0.001)
(check-within (nth-root 2 625 0.01) 25 0.01)
(check-within (nth-root 3 64 0.001) 4 0.001)
(: nth-root (natural natural real -> real))
(define nth-root
  (lambda (n x eps) (root-iter 1 1 n x eps)))

(: root-iter (real real natural natural real -> real))
(define root-iter
  (lambda (current last n x eps)
    (if (good-enough? current n x eps)
        current
        (root-iter (improve last n x) current n x eps))))

(: improve (real natural natural -> real))
(define improve
   (lambda (last n x)
    (* (/ 1 n)
       (+ (/ x
              (expt last (- n 1)))
          (* (- n 1)
              last)))))

(: good-enough? (real natural natural real -> boolean))
(define good-enough?
   (lambda (current n x eps)
    (< (abs (- (expt current n) x)) eps)))
4

1 回答 1

0

几乎可以肯定的是,您在这里使用的是精确算术。在这种特殊情况下,这将是代价高昂的,因为你的数学都是有理数的;你的分子和分母会变得很大。进入不精确的算术,您应该会看到性能的重大改进(请注意,以精度为代价)。

如果您正在处理精确的数字,Racket(以及一般的 Scheme)会为您提供精确的算术。事实证明,您从迭代到迭代改进猜测的方式都使用精确数字!:P

要确认此效果,请尝试:(nth-root 5 243.0 0.001)。比较 与(nth-root 5 243 0.001),您应该会发现计算答案所需的时间有很大差异。

这就是为什么你会看到类似exact->inexactScheme 的函数。以及为什么您会在计算机中看到浮点(不精确)算术:您会遇到获得柏拉图式答案非常昂贵的情况,并且对于许多应用程序,您可以容忍不精确性。

(虽然不是在金融领域。在处理金钱时不要使用不准确的数字,否则你会让某人非常非常不开心。)

于 2013-11-14T08:15:26.080 回答