Created
July 14, 2015 16:03
-
-
Save ikr7/954c3fd9773a817fc5ea to your computer and use it in GitHub Desktop.
This file contains 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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset='UTF-8'> | |
<link rel='stylesheet' href='./main.css'> | |
</head> | |
<body> | |
<div id='all'> | |
<h1>モンテカルロ法による円周率算出</h1> | |
<canvas></canvas> | |
打つ点の数: | |
<input type='number' value='1000'> | |
<button>算出</button> | |
結果: <span></span> | |
</div> | |
</body> | |
<script src='./main.js'></script> | |
</html> |
This file contains 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
body { | |
font-family: sans-serif; | |
} | |
#all{ | |
max-width: 502px; | |
margin-left: auto; | |
margin-right: auto; | |
} | |
canvas{ | |
border: 1px solid #000; | |
} |
This file contains 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
var cvs = document.querySelector('canvas'); | |
var w = 512, | |
h = 512 | |
cvs.width = w; | |
cvs.height = h; | |
var ctx = cvs.getContext('2d'); | |
var calculate = function(){ | |
console.time('calculate'); | |
var pointCount = document.querySelector('input').value; | |
var hit = 0; | |
var image = ctx.createImageData(w, h); | |
for (var i = 0; i < pointCount; i++) { | |
var x = Math.random() * w | 0; | |
var y = Math.random() * h | 0; | |
var pixelIndex = (w * (y - 1) + x) * 4 | |
if(Math.hypot(x - w / 2, y - h / 2) < w / 2){ | |
image.data[pixelIndex + 0] = 0xFF; | |
image.data[pixelIndex + 3] += 0x10; | |
hit++; | |
}else{ | |
image.data[pixelIndex + 2] = 0xFF; | |
image.data[pixelIndex + 3] += 0x10; | |
} | |
}; | |
ctx.putImageData(image, 0, 0); | |
console.timeEnd('calculate'); | |
return hit / pointCount * 4; | |
}; | |
document.querySelector('button').addEventListener('click', function(){ | |
var pi = calculate(); | |
document.querySelector('span').innerHTML = pi; | |
}, false); | |
document.querySelector('span').innerHTML = calculate(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment