Skip to content

Instantly share code, notes, and snippets.

@dev001hajipro
Created March 20, 2017 02:35
Show Gist options
  • Save dev001hajipro/79312ff44a4d0adcda0da1d4e15f6bf3 to your computer and use it in GitHub Desktop.
Save dev001hajipro/79312ff44a4d0adcda0da1d4e15f6bf3 to your computer and use it in GitHub Desktop.
JavaScriptとCanvasでモンテカルロ法で円周率を求める
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>モンテカルロ法</title>
<style>
canvas {
width :200px;
height:200px;
}
</style>
</head>
<body>
<canvas id="mycanvas" width="200" height="200"></canvas>
<div>π=<span id="piValue">0.0</span></div>
<script src="1.5.1.montecalro.js"></script>
</body>
</html>
"use strict";
let inCount = 0;
let counter = 0;
const piValue = document.getElementById('piValue');
function loop(canvas) {
counter++;
window.requestAnimationFrame(()=>{ loop(canvas)});
const ctx = canvas.getContext('2d');
const scale = canvas.width;
const x = Math.random(1);
const y = Math.random(1);
if (x * x + y * y < 1) {
ctx.strokeStyle = 'rgb(255,0,0)';
inCount++;
} else {
ctx.strokeStyle = 'rgb(0, 255,0)';
}
ctx.strokeRect(x * scale, y * scale, 1, 1);
piValue.innerHTML = (4*inCount) / counter;
}
loop(document.getElementById('mycanvas'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment