FileDocCategorySizeDatePackage
Pi.javaAPI DocExample2816Tue Dec 12 18:59:58 GMT 2000client

Pi

public class Pi extends Object implements Task

Fields Summary
private static final BigDecimal
ZERO
constants used in pi computation
private static final BigDecimal
ONE
private static final BigDecimal
FOUR
private static final int
roundingMode
rounding mode to use during pi computation
private int
digits
digits of precision after the decimal point
Constructors Summary
public Pi(int digits)
Construct a task to calculate pi to the specified precision.

    
                   
       
        this.digits = digits;
    
Methods Summary
public static java.math.BigDecimalarctan(int inverseX, int scale)
Compute the value, in radians, of the arctangent of the inverse of the supplied integer to the speficied number of digits after the decimal point. The value is computed using the power series expansion for the arc tangent: arctan(x) = x - (x^3)/3 + (x^5)/5 - (x^7)/7 + (x^9)/9 ...

        BigDecimal result, numer, term;
        BigDecimal invX = BigDecimal.valueOf(inverseX);
        BigDecimal invX2 = 
            BigDecimal.valueOf(inverseX * inverseX);

        numer = ONE.divide(invX, scale, roundingMode);

        result = numer;
        int i = 1;
        do {
            numer = 
                numer.divide(invX2, scale, roundingMode);
            int denom = 2 * i + 1;
            term = 
                numer.divide(BigDecimal.valueOf(denom),
                             scale, roundingMode);
            if ((i % 2) != 0) {
                result = result.subtract(term);
            } else {
                result = result.add(term);
            }
            i++;
        } while (term.compareTo(ZERO) != 0);
        return result;
    
public static java.math.BigDecimalcomputePi(int digits)
Compute the value of pi to the specified number of digits after the decimal point. The value is computed using Machin's formula: pi/4 = 4*arctan(1/5) - arctan(1/239) and a power series expansion of arctan(x) to sufficient precision.

        int scale = digits + 5;
        BigDecimal arctan1_5 = arctan(5, scale);
        BigDecimal arctan1_239 = arctan(239, scale);
        BigDecimal pi = arctan1_5.multiply(FOUR).subtract(
                                  arctan1_239).multiply(FOUR);
        return pi.setScale(digits, 
                           BigDecimal.ROUND_HALF_UP);
    
public java.lang.Objectexecute()
Calculate pi.

        return computePi(digits);