/** * Pi Series * -- this version tries to evaluate from the tail end! */ public class pi extends series { protected int sign = 1; protected long NoTerms = 1; protected double valpos = 0.0; protected double valneg = 0.0; /** * Parity of int number * * @param N input integer * @return 0 if even, 1 if odd */ public static int parity(int N){ return parity((long)N); } /** * Parity of long number * * @param N input integer * @return 0 if even, 1 if odd */ public static int parity(long N){ long m; m = N/2; if (N != 2*m) return 1; return 0; } /** * Constructor for Pi Series * * @param x is the argument for the series */ pi(double x){ param = x; n = -1; sign = -1; } /** * First initializes the first term of series */ public void first(){ term=1.0; sign=1; n=0; valpos = term; valneg = 0.0; val = valpos - valneg; } /** * First initializes the mth term of series * * @param m the last term of the series to sum */ public void last(long m){ NoTerms = m; n = (int)m; sign = -1; if (parity(m)==0) sign = 1; term = 1.0/(2*m+1); if (sign>0) {valpos = term; valneg = 0.0;} else {valneg = term; valpos = 0.0;} val = valpos - valneg; } /** * Advances to the next term in the series. */ public void nextTerm(){ n++; sign = -1*sign; term = 1.0/(2*n+1.0); if (sign>0) valpos = valpos + term; else valneg = valneg + term; val = val + sign*term; // inaccurate way //val = valpos - valneg; // accurate way //System.out.println("n=" + n + ", sign=" + sign + ", term=" +term); } /** * Backs up to the previous term in the series. */ public void prevTerm(){ n--; sign = -1*sign; term = 1.0/(2*n+1.0); if (sign>0) valpos = valpos + term; else valneg = valneg + term; val = val + sign*term; // inaccurate way } /** * Returns the value of the mth term in series * * @param m the index of a term * @return the mth term */ public double termAt(int m){ first(); for (int i=0; i