用牛顿法求根

时间:2019-12-26 16:37:57

标签: scheme elisp sicp function-call fixed-point-iteration

我写了newton-method以从elisp中的Scheme示例中找到根,

#+begin_src emacs-lisp :session sicp :lexical t
(defun deriv(g)
  (lambda (x)
    (/ (- (funcall g (+ x dx)) (funcall g x))
       dx)))

(defvar dx 0.00001)
(defvar tolerance 0.00001)

(defun fixed-point(f guess)
  (defun close-enoughp(v1 v2)
    (< (abs (- v1 v2)) tolerance))
  (let ((next (funcall f guess)))
    (if (close-enoughp guess next)
        next
      (fixed-point f next))))

(defun newton-transform(g)
  (lambda (x)
    (- x (/ (funcall g x) (funcall (funcall #'deriv g) x)))))

(defun newton-method(g guess)
  (fixed-point (funcall #'newton-transform g) guess))

(defun curt(x)
  (newton-method (lambda (y) (- (* y y y) x))
                  1.0))

(curt 12)
#+end_src

#+RESULTS:
: 2.2894284851069058

它可以工作,但是要注意扭曲的代码:

(defun newton-transform(g)
  (lambda (x)
    (- x (/ (funcall g x) (funcall (funcall #'deriv g) x)))))

三个funcall,如果有更多的关闭深度,我就很难想象。

是否存在elisp问题的替代解决方案? (我猜它会使闭包贬值)

2 个答案:

答案 0 :(得分:2)

newton-transform中,(funcall #'deriv g)(deriv g)相同,因此您可以消除3个funcall中的一个。实际上,另外两个是必需的。

newton-method相同:将(funcall #'newton-transform g)替换为(newton-transform g)

PS 。我强烈建议将defun close-enoughpdefun fixed-point中移出或将其变成cl-flet。 Lisp不是Scheme。

PPS close-enoughp应该是close-enough-p

答案 1 :(得分:1)

可以简化几个函数调用,我们应该实现@sds关于函数名称和约定的建议-像这样:

(defvar dx 0.00001)
(defvar tolerance 0.00001)

(defun deriv (g)
  (lambda (x)
    (/ (- (funcall g (+ x dx)) (funcall g x))
       dx)))

(defun close-enough-p (v1 v2)
  (< (abs (- v1 v2)) tolerance))

(defun try (f guess)
  (let ((next (funcall f guess)))
    (if (close-enough-p guess next)
      next
      (try f next))))

(defun fixed-point (f first-guess)
  (try f first-guess))

(defun newton-transform (g)
  (lambda (x)
    (- x (/ (funcall g x)
            (funcall (deriv g) x)))))

(defun newton-method (g guess)
  (fixed-point (newton-transform g) guess))

(defun curt (x)
  (newton-method (lambda (y) (- (* y y y) x))
                 1.0))

请注意,调用先前定义和命名的函数(例如funcallderiv时,我们不需要使用newton-transform