Last active
November 13, 2015 12:53
-
-
Save st98/8911925 to your computer and use it in GitHub Desktop.
円周率。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (function () { | |
| var randint = function (min, max) { | |
| if (max == null) { | |
| max = min; | |
| min = 0; | |
| } | |
| return Math.floor(Math.random() * (max - min + 1) + min); | |
| }; | |
| var plot = function (ctx, x, y, color) { | |
| if (color == null) { | |
| color = 'rgb(0, 0, 0)'; | |
| } | |
| ctx.fillStyle = color; | |
| ctx.fillRect(x - 2, y, 5, 1); | |
| ctx.fillRect(x, y - 2, 1, 5); | |
| }; | |
| var judge = function (x0, y0, r, x1, y1) { | |
| return (x0 - x1) * (x0 - x1) + (y0 - y1) * (y0 - y1) < r * r; | |
| }; | |
| (function init(num) { | |
| var cv, ctx, div, txt; | |
| var red, blue; | |
| var time; | |
| var i, k; | |
| cv = document.createElement('canvas'); | |
| div = document.createElement('div'); | |
| txt = document.createTextNode(''); | |
| div.style.fontSize = 'small'; | |
| div.style.fontFamily = 'Consolas, monospace'; | |
| cv.width = cv.height = 200; | |
| cv.style.border = '1px solid rgb(0, 0, 0)'; | |
| ctx = cv.getContext('2d'); | |
| red = 'rgb(127, 0, 0)'; | |
| blue = 'rgb(0, 0, 127)'; | |
| i = 1; | |
| k = 0; | |
| time = setInterval(function () { | |
| var x, y, j; | |
| x = randint(200); | |
| y = randint(200); | |
| j = judge(0, 200, 200, x, y); | |
| if (j) { | |
| k++; | |
| } | |
| plot(ctx, x, y, j ? blue : red); | |
| txt.textContent = 'π: ' + 4 * k / i; | |
| if (i >= num) { | |
| clearInterval(time); | |
| } | |
| i++; | |
| }, 1000 / 60); | |
| div.appendChild(txt); | |
| document.body.appendChild(div); | |
| document.body.appendChild(cv); | |
| })(10000); | |
| }).call(this); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment