Java Pi calculator getting stuck

I would rather use this code for the PI approach from the rectangles approximates:

    int rectangleCount = 100;
    double width = 0.0;
    double pi = 0.0;
    double height = 0.0;
    double radius = 1.0;
    
    for (int i = 1; i <= rectangleCount; i++) {
        
        width = (double)i / rectangleCount;
        
        height = Math.sqrt(radius - width*width);
        
        pi = pi + (radius/rectangleCount) *height;
    }
    pi = pi + 1.0/rectangleCount; //first rectangle

    System.out.println(pi*4);

Basically the count of the rectangles you choose, doesn’t matter. The first rectangle always has the same radius and width, while the rest of the rectangles can be calculated in the for loop.

Leave a Comment