Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: PI (π) Calculator

Is there a way to calculate pi in Javascript? I know there you can use Math.PI to find pie like this:

var pie = Math.PI;
alert(pie); // output "3.141592653589793"

but this is not accurate. What I want is to be able to calculate it, to have as many digits as you want, not anything like pie = 3.141592.... But still, what I want is not have just have some more digits, but as much as you can (like having one thousand digits, but I need more).

like image 329
Cai Haoyang Avatar asked Apr 14 '26 14:04

Cai Haoyang


1 Answers

Here is an implementation of a streaming algorithm described by Jeremy Gibbons in Unbounded Spigot Algorithms for the Digits of Pi (2004), Chaper 6:

function * generateDigitsOfPi() {
    let q = 1n;
    let r = 180n;
    let t = 60n;
    let i = 2n;
    while (true) {
        let digit = ((i * 27n - 12n) * q + r * 5n) / (t * 5n);
        yield Number(digit);
        let u = i * 3n;
        u = (u + 1n) * 3n * (u + 2n);
        r = u * 10n * (q * (i * 5n - 2n) + r - t * digit);
        q *= 10n * i * (i++ * 2n - 1n);
        t *= u;
    }
}

// Demo
let iter = generateDigitsOfPi();

let output = document.querySelector("div");
(function displayTenNextDigits() {
    let digits = "";
    for (let i = 0; i < 10; i++) digits += iter.next().value;
    output.insertAdjacentHTML("beforeend", digits);
    scrollTo(0, document.body.scrollHeight);
    requestAnimationFrame(displayTenNextDigits);
})();
div { word-wrap:break-word; font-family: monospace }
<div></div>
like image 164
trincot Avatar answered Apr 16 '26 03:04

trincot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!