SICPの勉強 問題1.31
SICP1.3.1の問題1.31を解いてみる。
productのrecursive process版:
(defn product [f a next b] (if (> a b) 1 (* (f a) (product f (next a) next b))))
iterative process版:
(defn product [f a next b] (loop [a a result 1] (if (> a b) result (recur (next a) (* (f a) result)))))
Idiomatic clojure版:
(defn product [f a next b] (->> (iterate next a) (take-while #(<= % b)) (map f) (apply *)))
factorialの定義:
(defn factorial [n] (product 1 inc n))
πの近似:
(def n 10000) (def pi (* 4.0 (/ (/ (product sq (bigint 4) #(+ 2 %) (* 2 n)) n) (product sq (bigint 3) #(+ 2 %) (* 2 n)))))
結果:3.141671194387856
productの中で*'
としたほうが、bigintを直接呼ぶより良かった気がする。