This was a pretty straight forward program. I wrote the program in one file using two classes. The following is the methods and data of the classes. The output of the pi program displays the first 10 iterations of the infinite series, then calculates pi to 3.14, 3.141, 3.145 and 3.14159 precision (reporting how many iterations it takes). The compiled pi.class is here and the compiled class ShowPI.class is here.
public class pi
This is the public class which is executed (contains
the main() function). It calls the ShowPI class which does all the
calculations and displays.
methods
public static void main(...) - Shows the
first ten iterations of the infinite series, then shows how long it takes
to calculate PI to the precision requested above.
class ShowPI
This class does all the work of the program.
It calculates PI by adding the next number in the infinite series to the
current value of PI.
data
m_dPI - current value of PI (calculated
from infinite series)
m_dDivideBy - next number to divide by
(incremented by 2 everytime)
m_dSubtract - whether to add or subtract
(multiplied by -1 to alternate)
m_nCount - current number of iterations
of the infinite series
methods
series_calculate_next() - calculates the
next value in the series.
display_current_PI() - displays the current value of PI. Prints: "Approximated PI: x.xxx after n iterations." where x.xxx is the current calculated value of PI (m_dPI) and n is the number of iterations (m_nCount).
show_iterations(int nIter) - calculates and displays nIter values of PI..
show_PI_at(double dRequestedPI, double dPrecision)
- Iterates series until PI is equal to dRequestedPI to the dPrecision
precision (i.e., until (m_dPI - dRequestedPI < dPrecision)
&& (m_dPI - dRequestedPI > 0).