This is my Clojure solution to Chapter 1, Exercise 29:
(ns sicp.ch1.ex29
(:require [sicp.ch1.ex15 :as ch1-ex15]))
(defn sum
[term a succ b]
(if (> a b)
0
(+ (term a)
(sum term (succ a) succ b))))
(defn integral
[f a b dx]
(* (sum f (+ a (/ dx 2.0)) (partial + dx) b)
dx))
(defn integral-simpson
[f a b n]
(let [h (/ (- b a) n)]
(* (sum #(let [m (cond
(zero? %) 1
(= n %) 1
(even? %) 2
(odd? %) 4)]
(* m (f (+ a (* % h)))))
0
inc
n)
(/ h 3))))
(integral ch1-ex15/cube 0 1 0.01) ; => 0.24998750000000042
(integral ch1-ex15/cube 0 1 0.001) ; => 0.249999875000001
(double (integral-simpson ch1-ex15/cube 0 1 100)) ; => 0.25
(double (integral-simpson ch1-ex15/cube 0 1 1000)) ; => 0.25
(ns sicp.ch1.ex29
(:require [sicp.ch1.ex15 :as ch1-ex15]))
(defn sum
[term a succ b]
(if (> a b)
0
(+ (term a)
(sum term (succ a) succ b))))
(defn integral
[f a b dx]
(* (sum f (+ a (/ dx 2.0)) (partial + dx) b)
dx))
(defn integral-simpson
[f a b n]
(let [h (/ (- b a) n)]
(* (sum #(let [m (cond
(zero? %) 1
(= n %) 1
(even? %) 2
(odd? %) 4)]
(* m (f (+ a (* % h)))))
0
inc
n)
(/ h 3))))
(integral ch1-ex15/cube 0 1 0.01) ; => 0.24998750000000042
(integral ch1-ex15/cube 0 1 0.001) ; => 0.249999875000001
(double (integral-simpson ch1-ex15/cube 0 1 100)) ; => 0.25
(double (integral-simpson ch1-ex15/cube 0 1 1000)) ; => 0.25
No comments:
Post a Comment