計算機科学のブログ

Building Abstractions with Functions - The Elements of Programming - Example: Square Roots by Newton's Method - cube roots

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.1(The Elements of Programming)、1.1.7(Example: Square Roots by Newton’s Method)、Exercise 1.8の解答を求めてみる。

コード

let abs = Math.abs;

function cube(x) {
    return x * x * x;
}
function improve(guess, x) {
    return (x / guess ** 2 + 2 * guess) / 3;
}
function is_good_enough(previous_guess, guess) {
    return abs(1 - guess / previous_guess) < 0.001;
}
function cube_root_iter(previous_guess, guess, x) {
    return is_good_enough(previous_guess, guess) ?
        guess :
        cube_root_iter(guess, improve(guess, x), x);
}
function cube_root(x) {
    return cube_root_iter(2 * x, x, x);
}

for (const x of [8, 27, 64, 1000, 1e9, 1e-9]) {
    console.log(`√${x}${cube_root(x)}`);
}

入出力結果(Terminal, Zsh)

% node answer1.8.js
√8 ≈ 2.000000001071189
√27 ≈ 3.0000000017936714
√64 ≈ 4.000000508638954
√1000 ≈ 10.000000002405413
√1000000000 ≈ 1000.0000000019248
√1e-9 ≈ 0.0010000000007855277
%