計算機プログラムの構造と解釈[第2版]
(翔泳社)
ハロルド エイブルソン (著)ジュリー サスマン (著)
ジェラルド・ジェイ サスマン (著)
Harold Abelson (原著)Julie Sussman (原著)
Gerald Jay Sussman (原著)和田 英一 (翻訳)
開発環境
- OS X Yosemite - Apple (OS)
- Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
- 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.1(プログラムの要素)、1.1.7(例: Newton法による平方根)、問題 1.7.を解いてみる。
その他参考書籍
- Instructor's Manual to Accompany Structure & Interpretation of Computer Programs
- プログラミングGauche (Kahuaプロジェクト (著), 川合 史朗 (監修), オライリージャパン)
- Scheme手習い
問題 1.7.
平方根の計算で使ったgood-enough?テストは、非常に小さい数の平方根をとる時には、すぐに許容値(今回の場合は0.001)より小さくなるので、十分な改善が行われず、効果的ではない。
大きい数の場合も、今度は十分すぎる改善が行われることになり、効果的ではない。
コード(BBEdit, Emacs)
sample7.scm
#!/usr/bin/env gosh
;; -*- coding: utf-8 -*-
(define a 1.0e-200)
(define b 1.0e+200)
(define square (lambda (x) (* x x)))
(define (improve guess x)
(average guess (/ x guess)))
(define average (lambda (x y) (/ (+ x y) 2)))
(define (good-enough? guess x)
(< (abs (- (square guess) x)) 0.001))
(define (sqrt-iter guess x)
(if (good-enough? guess x)
guess
(sqrt-iter (improve guess x)
x)))
(define (sqrt x)
(sqrt-iter 1.0 x))
(define x (sqrt a))
(print x)
(print (square x))
(print (- (square x) a))
(define y (sqrt b))
(print y)
(print (square y))
(print (- (square y) x))
;; 改善
(define (good-enough? guess-old guess-mew)
(< (abs (- guess-old guess-mew))
(* guess-mew 0.001)))
(define (sqrt-iter old-guess new-guess x)
(if (good-enough? old-guess new-guess)
new-guess
(sqrt-iter new-guess
(improve new-guess x)
x)))
(define (sqrt x)
(sqrt-iter 1.0 2.0 x))
(define x (sqrt a))
(print x)
(print (square x))
(print (- (square x) a))
(define y (sqrt b))
(print y)
(print (square y))
(print (- (square y) x))
入出力結果(Terminal(gosh), REPL(Read, Eval, Print, Loop))
$ ./sample7.scm 0.03125 9.765625e-4 9.765625e-4 1.0e100 1.0e200 1.0e200 1.0000000000013873e-100 1.0000000000027745e-200 2.774504132969674e-212 1.0000000000013873e100 1.0000000000027746e200 1.0000000000027746e200 $
0 コメント:
コメントを投稿