# 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

- 5
A useful text editor is an essential component of any personal computer. Every day we need to make notes, compose documents, and record vital pieces of information. We depend on our text editor. Microsoft provided...

- 12
Data Hiding is an aspect of Object Oriented Programming (OOP) that allows developers to protect private data and hide implementation details. In this tutorial we examine basic data hiding techniques in Java.

- 86
Ever been to a NASCAR race? I thought not. Here are my top 10 reasons why NASCAR racing doesn't rock.

## Comments 3 comments

Thanks for the code

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

c nul