2017年4月29日土曜日

開発環境

Think Perl 6: How to Think Like a Computer Scientist (Laurent Rosenfeld(著)、Allen B. Downey(著)、Oreilly & Associates Inc)の Part 1(Starting with the basics)、Chapter 6(Iteration)の Exercises 6-1、6-2. を JavaScript で取り組んでみる。

Exercises 6-1、6-2.

コード(Emacs)

HTML5

<pre id="output0"></pre>
a = <input id="a0" type="number" min="0" step="1" value="50">
ε = <input id="e0" type="number" min="0" value="0.000000000000001">
<br>
<button id="run0">run</button>
<button id="clear0">clear</button>

<script src="sample1.js"></script>

JavaScript

let btn0 = document.querySelector('#run0'),
    btn1 = document.querySelector('#clear0'),
    pre0 = document.querySelector('#output0'),
    input_a = document.querySelector('#a0'),
    input_e = document.querySelector('#e0'),
    inputs = [input_a, input_e],
    p = (x) => pre0.textContent += x + '\n',
    range = (start, end, step=1) => {
        let result = [];
        for (let i = start; i < end; i += step) {
            result.push(i);
        }
        return result;
    };

let sqrt = (a) => {
    let x = 1;
    for (;;) {
        let y = (x + a / x) / 2;
        if (y === x) {
            break;
        }
        x = y;
    }
    return x;
};

let testSquareRoot = () => {
    p('a sqrt(a) Math.sqrt(a) diff');
    p(
        range(1, 11)
            .map((a) => {
                let x = sqrt(a),
                    y = Math.sqrt(a);

                return `${a} ${x} ${y} ${Math.abs(x - y)}`;
            })
            .join('\n')
    );
};

let factorial = (n) => {
    let iter = (i, result) => i === 0 ? result : iter(i - 1, i * result);

    return iter(n, 1);
};

let term = (k) =>
    factorial(4 * k) * (1103 + 26390 * k) /
    (Math.pow(factorial(k), 4) * Math.pow(396, 4 * k));
    
let estimatePi = (epsilon) => {
    let sum = 0;
    let k = 0;
    for (;;) {
        let t = term(k);
        sum += t;
        if (t < epsilon) {
            break;
        }
        k += 1;
    }
    return 1 / (2 * Math.sqrt(2) / 9800 * sum);
};


let output = () => {
    p('1.');
    testSquareRoot();
    
    let a = parseInt(input_a.value, 10),
        x = sqrt(a),
        y = Math.sqrt(a);
    p(`${a} ${x} ${y} ${Math.abs(x - y)}`);

    p('2.');
    let epsilon = parseFloat(input_e.value);
    let pi = estimatePi(epsilon);
    p('estimatePi Math.PI diff');
    p(`${pi} ${Math.PI} ${Math.abs(pi - Math.PI)}`);
};

inputs.forEach((input) => input.onchange = output);
btn0.onclick = output;
btn1.onclick = () => pre0.textContent = '';

output();

a = 
ε = 

0 コメント:

コメントを投稿

Comments on Google+: