Monday, October 20, 2014

Calculating the value of PI accurately to 5 decimal places

This program uses the Gregory-Leibniz series for calculating the value of PI. Note that this series is slow and there exist other faster algorithms for calculating the value of PI. 

A simple infinite series for π is the Gregory–Leibniz series:
 \pi = \frac{4}{1} - \frac{4}{3} + \frac{4}{5} - \frac{4}{7} + \frac{4}{9} - \frac{4}{11} + \frac{4}{13} - \cdots
As individual terms of this infinite series are added to the sum, the total gradually gets closer to π, and – with a sufficient number of terms – can get as close to π as desired. It converges quite slowly, though – after 500,000 terms, it produces only five correct decimal digits of π.

public class PI { 

    static float calculate() {
        float denom = 1, sum = 0, numerator = -4.0f;   
        for(int i=0;i<500000;++i){
            float nextTerm = (numerator=-numerator) / (denom);  
            sum += nextTerm;  
        return sum;
    public static void main(String[] args) { 


No comments:

Post a Comment