2017年4月8日土曜日

開発環境

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 5(Iteration)の Boolean functions の Exercise 6-2.を JavaScript で取り組 んでみる。

Exercise 6-2.

コード(Emacs)

HTML5

ε = <input id="e0" type="number" value="0.000000000000001">
<button id="run0">run</button>
<button id="clear0">clear</button>
<pre id="output0"></pre>

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

JavaScript

let btn0 = document.querySelector('#run0'),
    btn1 = document.querySelector('#clear0'),
    input_e = document.querySelector('#e0'),
    pre0 = document.querySelector('#output0');

let factorial = (n) => {
    let iter = (i, result) => {
        if (i === n) {
            return result;
        }
        return iter(i + 1, i * result);
    };
    return iter(n, 1);
};

let term = (k) => {
    let num = factorial(4 * k) * (1103 + 26390 * k),
        den = Math.pow(factorial(k), 4) * Math.pow(396, 4 * k);

    return num / den;
};

let estimatePi = (epsilon) => {
    let result = 0,
        k = 0,
        t = term(k);
    
    for (; t >= epsilon;) {
        result += t;
        k += 1;
        t = term(k);
    }
    pre0.textContent += `n = ${k}\n`;
    return 1 / (2 * Math.sqrt(2) / 9801 * result);
};

let output = () => {
    let e = parseFloat(input_e.value),
        pi = estimatePi(e);        
    pre0.textContent +=
        `estimate pi: ${pi}\n` +
        `Math.PI:     ${Math.PI}\n` +
        `difference: ${Math.abs(pi - Math.PI)}\n`;
};
    

btn0.onclick = output;
btn1.onclick = () => {
    pre0.textContent = '';
};

output();
ε =










 
						

0 コメント:

コメントを投稿

Comments on Google+: