5

I thought I found a way to compute PI, but I actually just found a super shitty way to print a variable..

const precision = 1000000

// convert degree to radians
function rad(degree){
return degree * (Math.PI/180);
}
function calculatePI(){
// [x, y]
// take first point on start of unic circle
const point1 = [Math.cos(0) , Math.sin(0)];
// take second point at 0.001 degree
const point2 = [Math.cos(rad(1/precision)), Math.sin(rad(1/precision))];

// Estimate 0.001 degree of circle
const dist = Math.sqrt((point2[0] - point1[0] ) ** 2 + (point2[1] - point1[1]) ** 2);
// Calculate full circle
const perimeter = dist * precision * 180;
return perimeter;
}
console.log(calculatePI());

Comments
  • 17
    The best way to find pi always starts by using Math.Pi
  • 1
    Pi is already encoded in sin and cos. It makes no sense to pass fractions of pi to sin/cos to calculate pi.

    You could use the Leibniz formula instead:
    https://en.m.wikipedia.org/wiki/...
  • 2
    ```
    calculatePI() {
    return Math.PI;
    }

    console.log(calculatePI());
    ```

    👌
  • 1
    #include <math.h>

    //<-----when you do not want to use: M_PI :-)

    #define MATH_PI 4.0 * atan(1.0)

    int main(){

    printf("PI: %lf\n", MATH_PI);

    }
Add Comment