2017年4月19日水曜日

開発環境

The Art of Computer Programming Volume 1 Fundamental Algorithms Third Edition 日本語版(Donald E. Knuth (著)、青木 孝 (著)、筧 一彦 (著)、鈴木 健一 (著)、長尾 高弘 (著)、有澤 誠 (その他)、和田 英一 (その他)、ドワンゴ)の第1章(基礎概念)、1.2(数学的な基礎)、演習問題9を取り組んでみる。


  1. ( 1a ) n 1na ( 1a ) n+1 ( 1na )( 1a ) =1naa+n a 2 1( n+1 )a

コード(Emacs)

HTML5

<div id="graph0"></div>
a = <input id="a0" type="number" min="0.01" step="0.01" max="0.99" value="0.50">
n = <input id="n0" type="number" min="0" step="1" value="10">
<br>
<button id="draw0">draw</button>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.6/d3.min.js" integrity="sha256-5idA201uSwHAROtCops7codXJ0vja+6wbBrZdQ6ETQc=" crossorigin="anonymous"></script>

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

JavaScript

let div0 = document.querySelector('#graph0'),
    input0 = document.querySelector('#a0'),
    input1 = document.querySelector('#n0'),
    inputs = [input0, input1],
    width = 600,
    height = 600,
    padding = 20,
    btn0 = document.querySelector('#draw0'),
    f = (a, n) => Math.pow(1 - a, n),
    g = (a, n) => 1 - n * a;

let draw = () => {
    let points = [],
        a = parseFloat(input0.value),
        n = parseInt(input1.value, 10);
    
    for (let i = 0; i < n + 1; i += 1) {
        points.push([i, f(a, i)]);
    }
    for (let i = 0; i < n + 1; i += 1) {
        points.push([i, g(a, i)]);
    }
    let min = Math.min(0, ...points.map((x) => x[0]), ...points.map((x) => x[1])),
        max = Math.max(n + 1, ...points.map((x) => x[0]), ...points.map((x) => x[1]));
    let xscale = d3.scaleLinear()
        .domain([min, max])
        .range([padding, width - padding]);
    let yscale = d3.scaleLinear()
        .domain([min, max])
        .range([height - padding, padding]);

    let xaxis = d3.axisBottom().scale(xscale);
    let yaxis = d3.axisLeft().scale(yscale);
    div0.innerHTML = '';
    let svg = d3.select('#graph0')
        .append('svg')
        .attr('width', width)
        .attr('height', height);

    let t = points.length / 2;
    svg.selectAll('circle')
        .data(points)
        .enter()
        .append('circle')
        .attr('cx', (d) => xscale(d[0]))
        .attr('cy', (d) => yscale(d[1]))
        .attr('r', 2)
        .attr('fill', (d, i) => i < t ? 'red' : 'blue');

    svg.append('g')
        .attr('transform', `translate(0, ${height - padding})`)
        .call(xaxis);

    svg.append('g')
        .attr('transform', `translate(${padding}, 0)`)
        .call(yaxis);
}

inputs.forEach((input) => input.onchange = draw);
btn0.onchange = draw;

draw();
a = n =

0 コメント:

コメントを投稿

Comments on Google+: