計算機プログラムの構造と解釈[第2版]
(翔泳社)
ハロルド エイブルソン (著) ジュリー サスマン (著)
ジェラルド・ジェイ サスマン (著)
Harold Abelson (原著) Julie Sussman (原著)
Gerald Jay Sussman (原著) 和田 英一 (翻訳)
開発環境
- OS X Yosemite - Apple (OS)
- Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
- Scheme (プログラミング言語)
- k-scheme, Gauche (処理系)
計算機プログラムの構造と解釈[第2版](ハロルド エイブルソン (著)、ジュリー サスマン (著)、ジェラルド・ジェイ サスマン (著)、Harold Abelson (原著)、Julie Sussman (原著)、Gerald Jay Sussman (原著)、和田 英一 (翻訳)、翔泳社、原書: Structure and Interpretation of Computer Programs (MIT Electrical Engineering and Computer Science)(SICP))の1(手続きによる抽象の構築)、1.3(高階手続きによる抽象)、1.3.4(値として返される手続き)、問題 1.40.を解いてみる。
その他参考書籍
- Instructor's Manual to Accompany Structure & Interpretation of Computer Programs
- プログラミングGauche (Kahuaプロジェクト (著), 川合 史朗 (監修), オライリージャパン)
- Scheme手習い
問題 1.40.
コード(BBEdit, Emacs)
(define square (lambda (x) (* x x)))
(define dx 0.00001)
(define deriv
(lambda (g)
(lambda (x)
(/ (- (g (+ x dx)) (g x))
dx))))
(define newton-transform
(lambda (g)
(lambda (x)
(- x
(/ (g x)
((deriv g) x))))))
(define newtons-method
(lambda (g guess)
(fixed-point (newton-transform g) guess)))
(define abs
(lambda (x)
(if (< x 0)
(* -1 x)
x)))
(define tolerance 0.00001)
(define fixed-point
(lambda (f first-guess)
(define close-enough?
(lambda (v1 v2)
(< (abs (- v1 v2))
tolerance)))
(define try
(lambda (guess)
((lambda (next)
(if (close-enough? guess next)
next
(try next)))
(f guess))))
(try first-guess)))
(define cubic
(lambda (a b c)
(lambda (x)
(+ (* (square x) x)
(+ (* a (square x))
(+ (* b x)
c))))))
(define x1 (newtons-method (cubic 0 0 0) 1))
(define x2 (newtons-method (cubic 1 0 0) 1))
(define x3 (newtons-method (cubic 0 1 0) 1))
(define x4 (newtons-method (cubic 0 0 1) 1))
(define x5 (newtons-method (cubic 2 3 4) 1))
x1
x2
x3
x4
x5
(* (square x1)
x1)
(+ (* (square x2)
x2)
(square x2))
(+ (* (square x3)
x3)
x3)
(+ (* (square x4)
x4)
1)
(+ (* (square x5)
x5)
(+ (* 2 (square x5))
(+ (* 3 x5)
x5)))
入出力結果(Terminal(gosh), REPL(Read, Eval, Print, Loop))
$ kscheme < sample40.scm In : Out: square In : Out: dx In : Out: deriv In : Out: newton-transform In : Out: newtons-method In : Out: abs In : Out: tolerance In : Out: fixed-point In : Out: cubic In : Out: x1 In : Out: x2 In : Out: x3 In : Out: x4 In : Out: x5 In : Out: 0.265319902917829849388e-4 In : Out: 0.112274291004356635239e-4 In : Out: 0.366810201913271171631e-16 In : Out: -0.999999999999986396134e0 In : Out: -0.165062919143309808332e1 In : Out: 0.186771019385640735849e-13 In : Out: 0.12605657948072843154e-9 In : Out: 0.366810201913271171631e-16 In : Out: 0.408115985439916662148e-13 In : Out: -0.565062919140434453101e1 In : $
0 コメント:
コメントを投稿