Apurva Nagar
Apurva Nagar

Reputation: 55

How to calculate value of Pi using Leibniz method faster?

The program I am using for calculating Pi using Leibniz series/formula is working correctly. Below is my program:-

    public class PiFinder
{
    public static void main()
    {
        double count = 99999.0;
        double denominator = 1.0;
        double pi = 0.0;
        for (int x=0; x <= count; x++)
        {
            if (x%2==0)
            {
                pi = pi + (1/denominator);
            }
            else
            {
                pi = pi - (1/denominator);
            }
            denominator = denominator + 2;
        }
        pi = pi * 4; 
        System.out.println("Value of Pie: " + pi);
    }
}

If I increase the value of count to 999999999.0(9 digits) or 9999999999.0(10 digits), JVM keeps on running. How can I decrease the time JVM takes for interpreting?

Upvotes: 1

Views: 920

Answers (2)

Axel Kemper
Axel Kemper

Reputation: 11322

The following version uses integer datatypes which makes it much faster:

public class PiFinder {
    public static void main(String[] args) {
        int count = 99999999;
        int denominator = 1;
        double pi = 0.0;

        for (int x = 0; x <= count; x++) {
            //  equivalant but not faster:
            //  ((x & 1) == 0)
            if (x % 2 == 0) {
                //  note the 1.0:
                //  it converts the right-hand-side to double
                pi += (1.0 / denominator);
            } else {
                pi -= (1.0 / denominator);
            }
            denominator += 2;
        }
        pi = pi * 4;
        System.out.println("Value of Pie: " + pi);
        System.out.println("ciao!");
    }
}

Upvotes: 0

user1978011
user1978011

Reputation: 3589

Modulo operations are painfully slow, however they can be substituted by bit operations if the modulo is a power of two and the value is an integer. To benefit from that, make your counter x an integer type.

Upvotes: 0

Related Questions