1. 程式人生 > >蒙特卡洛方法求解圓周率

蒙特卡洛方法求解圓周率

nsf click oct tco store can 20px ane type

代碼:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>蒙特卡洛方法求解圓周率</title>
    <style>
        body {
            -moz-user-select: none; /*火狐*/
            -webkit-user-select: none; /*webkit瀏覽器*/
            -ms-user-select: none; /*IE10
*/ -khtml-user-select: none; /*早期瀏覽器*/ user-select: none; } .container { width: 500px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); height: 700px; box-shadow
: 0 0 10px 1px #0000002e; text-align: center; } .btn-container { padding: 0 20px 20px; } .btn-container span { display: inline-block; border: 1px solid transparent; border-radius: 5px; line-height: 1.5; padding
: 0 10px; box-sizing: border-box; width: 49%; text-align: center; } .btn-container span:hover { /*background: black;*/ border: 1px solid black; cursor: pointer; } </style> </head> <body> <div class="container"> <h1>蒙特卡洛方法求解圓周率</h1> <canvas id="canvas" width="500" height="500" style="background: bisque"> </canvas> <div class="btn-container"> <span id="btnCalc">增加一萬個點</span> <span id="btnClear">清除點</span> <p id="panel">計算結果</p> </div> </div> <script> var canvas = document.getElementById(canvas); var ctx = canvas.getContext(2d) ctx.translate(250, 250); //坐標移動到圓心 document.getElementById(btnCalc).addEventListener(click, function () { calc() }); document.getElementById(btnClear).addEventListener(click, function () { clear() }); /** * 繪制黑色框 */ function square() { ctx.beginPath(); ctx.moveTo(-150, 150); ctx.lineTo(-150, -150); ctx.lineTo(150, -150); ctx.lineTo(150, 150); ctx.closePath(); ctx.stroke() } clear(); var redNum = 0; var blackNum = 0; /** * 繪制圓點 * @param x * @param y * @param r */ function drawCircle(x, y, r) { r = r || 1; ctx.save(); if (x * x + y * y < 150 * 150) { redNum++; ctx.fillStyle = #f00 } else { blackNum++; ctx.fillStyle = #000 } ctx.beginPath(); ctx.arc(x, y, r, 0, 2 * Math.PI); ctx.fill(); ctx.restore() } /** * 隨機增加10000個點 */ function calc() { square(); for (var i = 0; i < 10000; i++) { drawCircle(Math.random() * 300 - 150, Math.random() * 300 - 150); } var span = document.getElementById(panel); span.innerHTML = 在圓形內的共有 + redNum + 個, + 在圓形外的共有 + blackNum + 單位圓與正方形數量之比是 + (redNum / (blackNum + redNum)).toFixed(3) + 由此計算值為 + <span style="color: red;text-align: left"> + (redNum * 4 / (blackNum + redNum)).toFixed(5) + </span> } /** * 清楚繪制的畫布 */ function clear() { ctx.beginPath(); ctx.moveTo(-150, 150); ctx.lineTo(-150, -150); ctx.lineTo(150, -150); ctx.lineTo(150, 150); ctx.closePath(); ctx.fillStyle = #fff; ctx.fill(); square() } </script> </body> </html>

碼雲地址:https://gitee.com/Kongdp/CalcPi

蒙特卡洛方法求解圓周率