SICPの勉強 問題1.40
SICP1.3.4の問題1.40を解いてみる。
x3 + ax2 + bx + c = 0の解をNewton's Methodで解く関数を作成する。
とりあえずNewton's Methodの実装:
(defn deriv [g] (let [dx 0.00001] (fn [x] (/ (- (g (+ x dx)) (g x)) dx)))) (defn newton-transform [g] (fn [x] (- x (/ (g x) ((deriv g) x))))) (defn newtons-method [g guess] (fixed-point (newton-transform g) guess))
fixed-pointは以前と同じ、clojureっぽいやつを使った。
後は愚直に記述するだけ:
(defn cubic [a b c] (fn [x] (+ (* x x x) (* a x x) (* b x) c)))
これを使うと、例えばx3 + 2x2 + 3x + 4 = 0の解が(一つ)簡単に出せる。
(newtons-method (cubic 2 3 4) 1.0)
fixed-pointは結構面白い。あまり概念として利用したことがなかったのだが、これからは使えるところがあるか目を光らせていきたい。