Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.