JSFiddle - React, Tailwind, and code Playground
CSS
body {
background-color: #000;
}
#output {
font-family: Courier New, Courier, monospace;
font-size: 48px;
color: #FFF;
text-align: center;
margin-top: 40px;
}
JavaScript
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
var piCalculator = {
depth : 26, //Note: Binary-tree-recursion, increasing this value by 1 will double calculation time.
pi : 0,
decimalCount : 4,
output : document.getElementById("output"),
init : async function() {
this.output.innerHTML = 'Calculating...';
await sleep(100);
this.recurseCalculatePi(0, 0, 0);
},
recurseCalculatePi : function(x, y, d) {
var w = this.calculateFragment(x, y);
this.pi += w * w * 4;
if(d > this.depth) {
return;
}
this.recurseCalculatePi(x + w, y, d + 1);
this.recurseCalculatePi(x, y + w, d + 1);
if(d == 0) {
this.output.innerHTML = this.pi.toFixed(this.decimalCount);
}
},
calculateFragment : function(x, y) {
var b = y + x;
var c = (x * x + y * y - 1) / 2;
return (-b + Math.sqrt(b * b - 4 * c)) / 2;
}
};
piCalculator.init();