Approximate pi in Java

Introduction

This code illustrates a simple iterative method for approximating the value of pi. As we all know, pi represents the ratio of a circle's circumference to it's diameter. The number does not change, regardless of the size of the circle. Big circles and little circles all share the same value of π.

Pi is an irrational number. In other words, people that use π in their equations tend to be easily upset by seemingly insignificant issues. Mathematicians can be a touchy bunch and for that reason are not invited to many casual parties. Perhaps this is why they have their own conventions and university departments.

How does it work?

It works perfectly. As long as the floating point data items are not permitted to overflow, it works.

The floating point division in lines 22 and 23 are a weak point. As we all know, the float data type in Java supports about 6.5 digits, therefore we observe that floating point error begins to creep into the calculations rather quickly.

Future Work

Ambitious programmers and bored readers may wish to improve upon the algorithm by implementing a data type that resists precision loss with greater efficacy. Converting the calculations to use the double data type presents little challenge, but would improve resolution relatively significantly.

Another challenge might be to rewrite all calculations with the BigInteger class provided by Java. Throughput would drastically decrease, but precision would take a major leap forward.

// This method approximates pi through an interative calculation.
// It prints the result to stdout rather than return it.
// The calculation stops when a number between 3.14160 and 4.14159 is reached.
// This method could be easily enhanced by narrowing the range.
// A narrower range would yield a closer approximation of pi.
// Happy pi day!


public static void approxpi()         // Approximate pi
{
    double x =1;
    double y =3;
    int pass =0;
    double pi1 = 0;
    double pi2 = 0;

//    while (Math.abs(3.14160 -pi2)> .00001)
    while (!(pi2 <= 3.14160 && pi2 >= 3.14159))
    {
        pass=pass+1;
        pi1 = (4./x) - (4./y);    //given equation
        x=x+4;
        y=y+4;
        pi2 = pi2 +pi1;
    }
    System.out.print("\n\nValue of pi is approx.: "+pi2+", terms needed ="+pass);
}

More by this Author


Comments 3 comments

Saafir 6 years ago

Thanks for the code


seedling profile image

seedling 5 years ago

You might need to reformat the article since the code is disappearing under an advertisement.


banania 5 years ago

c nul

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working