計算機科学のブログ

Building Abstractions with Data - Introduction to Data Abstraction - Extended Exercise: Interval Arithmetic - division, error

Structure and Interpretation of Computer Programs: JavaScript Edition(Harold Abelson(著)、Gerald Jay Sussman(著)、Julie Sussman(著)、The MIT Press)のChapter 2(Building Abstractions with Data)、2.1(Introduction to Data Abstraction)、2.1.4(Extended Exercise: Interval Arithmetic)、Exercise 2.10の解答を求めてみる。

コード

function display(x) {
    return console.log(x);
}
function error(x) {
    display(x);
    return -1;
}
function math_min(...args) {
    return Math.min(...args);
}
function math_max(...args) {
    return Math.max(...args);
}
function pair(x, y) {
    return [x, y];
}
function head(z) {
    return z[0];
}
function tail(z) {
    return z[1];
}
function make_interval(x, y) {
    return pair(x, y);
}
function lower_bound(interval) {
    return head(interval);
}
function upper_bound(interval) {
    return tail(interval);
}
function mul_interval(x, y) {
    const p1 = lower_bound(x) * lower_bound(y);
    const p2 = lower_bound(x) * upper_bound(y);
    const p3 = upper_bound(x) * lower_bound(y);
    const p4 = upper_bound(x) * upper_bound(y);
    return make_interval(
        math_min(p1, p2, p3, p4),
        math_max(p1, p2, p3, p4)
    )
}
function div_interval(x, y) {
    const p1 = upper_bound(y);
    const p2 = lower_bound(y);
    return p1 * p2 <= 0 ?
        error("spans zero error") :
        mul_interval(
            x,
            make_interval(
                1 / p1,
                1 / p2
            )
        );
}

const x = make_interval(1, 2);
const y = make_interval(-1, 2);

display(x);
display(y);
display(mul_interval(x, y));
display(div_interval(x, y));

入出力結果(Terminal, Zsh)

% node answer2.10.js
[ 1, 2 ]
[ -1, 2 ]
[ -2, 4 ]
spans zero error
-1
%