2014年12月6日土曜日

[SICP] 問題 1.40 : Newton法

newtons-methodの手続きと一緒に
(newtons-method (cubic a b c) 1)
の形の式で使い, 三次式 x3 + ax2 + bx + c の零点を近似する手続き cubicを定義せよ.
Newton法のための手続きと問題文で指定されたcubic手続きを定義します.
(define dx 0.00001)

(define tolerance 0.00001)

(define (square x) (* x x))

(define (fixed-point f first-guess)
  (define (close-enough? v1 v2)
    (< (abs (- v1 v2)) tolerance))
  (define (try guess)
    (let ((next (f guess)))
      (if (close-enough? guess next)
          next
          (try next))))
  (try first-guess))

(define (deriv g)
  (lambda (x)
    (/ (- (g (+ x dx)) (g x))
       dx)))

(define (newton-transform g)
  (lambda (x)
    (- x (/ (g x) ((deriv g) x)))))

(define (newtons-method g guess)
  (fixed-point (newton-transform g) guess))

(define (cubic a b c)
  (lambda (x)
    (+ (* x x x)
       (* a x x)
       (* b x)
       c)))

(newtons-method (cubic 0 0 -10) 1)
実行例として10の三乗根を求めてみます.
ようこそ DrRacket, バージョン 6.1 [3m].
言語: Pretty Big; memory limit: 2048 MB.
> (newtons-method (cubic 0 0 -10) 1)
2.154434690031893
> (expt 2.154434690031893 3)
10.000000000000131
> 

0 件のコメント:

コメントを投稿