Home > other >  Figuring out the value for PI
Figuring out the value for PI

Time:11-15

Let's say I have a function called bars()

bars () {
 const bars = []
 for (let i = 0; i < this.numberOfBars; i  ) {
   bars.push(Math.sqrt(this.numberOfBars * this.numberOfBars - i * i))
 }
return bars
}
                

If I'm reducing the bars array to approximate PI, what should be on the right side of the arrow function?

PI = bars().reduce((a, b) =>

I tried adding the values and dividing by the number of bars, but I'm not getting anywhere near the approximation of Pi. I feel like there's a simple trick that I'm missing.

CodePudding user response:

Your funcion seems to list lengths of "bars" in a quarter of a circle, so we have to add them all up (to have the area of the quarter of a circle), then multiply by 4 (because there is 4 quarter) and the divide by this.numberOfBars ^ 2 because area = π * r^2, but like we have to know the radius, it is better using a pure function :

// Your function rewritten as a pure one
const bars = numberOfBars => {
    const bars = []

    for (let i = 0; i < numberOfBars; i  ) {
        bars.push(Math.sqrt(numberOfBars * numberOfBars - i * i))
    }

    return bars
}

// Here we take 1000 bars as an example but in your case you replace it by this.numberOfBars
// Sum them all up, multiply by 4, divide by the square of the radius
const PI = bars(1000).reduce((g, c) => g   c) * 4 / Math.pow(1000, 2)

console.log(PI)

CodePudding user response:

/** Approximates PI using geometry 
  * You get a better approximation using more bars and a smaller step size
*/
function approximatePI(numberOfBars, stepSize) {
    const radius = numberOfBars * stepSize;

    // Generate bars (areas of points on quarter circle)
    let bars = [];

    // You can think of i as some point along the x-axis
    for (let i = 0; i < radius; i  = stepSize) {
        let height = Math.sqrt(radius*radius - i*i)
        bars.push(height * stepSize);
    }

    // Add up all the areas of the bars 
    // (This is approximately the area of a quarter circle if stepSize is small enough)
    const quarterArea = bars.reduce((a, b) => a   b);

    // Calculate PI using area of circle formula
    const PI = 4 * quarterArea / (radius*radius)
    return PI;
}


console.log(`PI is approximately ${approximatePI(100_000, 0.001)}`);

CodePudding user response:

There is no reason to push all terms to an array, then to reduce the array by addition. Just use an accumulator variable and add all terms to it.


Notice that the computation becomes less and less accurate the closer you get to the end of the radius. If you sum to half of the radius, you obtain r²(3√3 π)/24, from which you can draw π.

(Though in any case, this is one of the worst methods to evaluate π.)

  • Related