我正在为我的编程课使用 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)))