Building Abstractions with Functions - Formulating Abstractions with Higher-Order Functions - Functions as General Methods - Finding fixed points of functions - infinite continued fraction, golden ratio, recursive process, iterative process
Structure and Interpretation of Computer Programs: JavaScript Edition(Harold Abelson(著)、Gerald Jay Sussman(著)、Julie Sussman(著)、The MIT Press)のChapter 1(Building Abstractions with Functions)、1.3(Formulating Abstractions with Higher-Order Functions)、1.3.3(Functions as General Methods)、Exercise 1.37-a、bの解答を求めてみる。
コード
console.log('a.');
// iterative process
function cont_frac_iter(n, d, k) {
function iter(i) {
return i === k ?
n(i) / d(i) :
n(i) / (d(i) + iter(i + 1));
}
return iter(1);
}
function iter_golden_ratio_iter(k) {
const x = 1 / cont_frac_iter(i => 1, i => 1, k);
console.log(`k = ${k}: ${x}`);
if (k < 20) {
iter_golden_ratio_iter(k + 1)
}
}
// 以下の出力結果よりk=12のときとわかる。
iter_golden_ratio_iter(1);
// recursive process
console.log('b.');
function cont_frac(n, d, k) {
function iter(i, result) {
return i === 0 ?
result :
iter(i - 1, n(i) / (d(i) + result));
}
return iter(k, 0);
}
function iter_golden_ratio(k) {
const x = 1 / cont_frac(i => 1, i => 1, k);
console.log(`k = ${k}: ${x}`);
if (k < 20) {
iter_golden_ratio(k + 1)
}
}
iter_golden_ratio(1);
入出力結果(Terminal, Zsh)
% node answer1.37.js
a.
k = 1: 1
k = 2: 2
k = 3: 1.5
k = 4: 1.6666666666666665
k = 5: 1.6
k = 6: 1.625
k = 7: 1.6153846153846154
k = 8: 1.619047619047619
k = 9: 1.6176470588235294
k = 10: 1.6181818181818184
k = 11: 1.6179775280898876
k = 12: 1.6180555555555558
k = 13: 1.6180257510729614
k = 14: 1.6180371352785146
k = 15: 1.6180327868852458
k = 16: 1.618034447821682
k = 17: 1.618033813400125
k = 18: 1.6180340557275543
k = 19: 1.6180339631667064
k = 20: 1.6180339985218037
b.
k = 1: 1
k = 2: 2
k = 3: 1.5
k = 4: 1.6666666666666665
k = 5: 1.6
k = 6: 1.625
k = 7: 1.6153846153846154
k = 8: 1.619047619047619
k = 9: 1.6176470588235294
k = 10: 1.6181818181818184
k = 11: 1.6179775280898876
k = 12: 1.6180555555555558
k = 13: 1.6180257510729614
k = 14: 1.6180371352785146
k = 15: 1.6180327868852458
k = 16: 1.618034447821682
k = 17: 1.618033813400125
k = 18: 1.6180340557275543
k = 19: 1.6180339631667064
k = 20: 1.6180339985218037
%