block by bricedev 33de9b3c78b442938d52

Monte-Carlo

Full Screen

Pi approximation using Monte-Carlo method

index.html

<!DOCTYPE html>
<meta charset="utf-8">
<style>

body {
  font: 10px sans-serif;
}

.axis path,
.axis line, .square {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

</style>
<body>
<script src="https://d3js.org/d3.v3.js"></script>
<script>

var width = 960,
    height = 700;

var numSamples = 0;
var formatPi = d3.format('.10f');
var rayon = 500;
var x = d3.scale.linear()
    .domain([0,1])
    .range([0, rayon]);

var y = d3.scale.linear()
    .domain([0,1])
    .range([0, -rayon]);

var xAxis = d3.svg.axis()
    .scale(x)
    .tickValues([0,0.5,1])
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(y)
    .tickValues([0.5,1])
    .orient("left");

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)
  .append("g")
    .attr("transform", "translate(" + (width/2 - rayon/2) + "," + (height/2 + rayon/2) + ")");

var value = svg.append("text")
  .attr("x", rayon/2)
  .attr("y", -rayon-40)
  .style("text-anchor","middle")
  .style("font-size","35px")
  .text("π = 0");

svg.append("circle")
  .attr("r",rayon)
  .style("fill","none")
  .style("stroke","black")
  .style("stroke-width",2);

svg.append("line")
  .attr("class", "square")
  .attr("x1",rayon)
  .attr("y1",0)
  .attr("x2",rayon)
  .attr("y2",-rayon);

svg.append("line")
  .attr("class", "square")
  .attr("x1",0)
  .attr("y1",-rayon)
  .attr("x2",rayon)
  .attr("y2",-rayon);

svg.append("g")
    .attr("class", "x axis")
    .call(xAxis);

svg.append("g")
    .attr("class", "y axis")
    .call(yAxis);

var blues = 0,
    reds = 0,
    pi = 0;

d3.timer(function() {
  var cx = Math.random(),
      cy = Math.random();

  if ((Math.pow(cx,2) + Math.pow(cy,2))< 1) {
    blues +=1;
    var color = "#66bd63"
  }else {
    reds +=1
    var color = "#f46d43"
  };
  
  pi = (blues / (blues + reds)) * 4; 
  
  value.text("π = " + formatPi(pi));

  svg.append("circle")
    .attr("cx",x(cx))
    .attr("cy",y(cy))
    .attr("r",3)
    .style("fill",color);
  
  return ++numSamples > 5000;
});

d3.select(self.frameElement).style("height", height + "px");

</script>