-1

I am trying calculating the term for Pi using the Taylor series. I want to keep adding terms until the last value of term is less than 1e-17. I have set the program right now at term = 31 because after that there is no change Pi = 3.141592653589794 error = 8.88178e - 16.

public static double compPi()
    {
        int terms1 = 31;
        int sg = 1, denom1 = 1;
        double sum = 1.0, denom2 = 1.0;
        for (int t = 2; t <= terms1; t++){
            denom1 += 2; denom2 *= 3;
            double term = 1.0/ (denom1 * denom2);
            sg *= -1;
            sum += sg * term;
        }
        double pi = Math.sqrt(12) * sum;
        return pi;
    }
The Head Rush
  • 3,157
  • 2
  • 25
  • 45
Stanmoonie
  • 31
  • 5
  • What's the problem? That the precision isn't as good as you want it? Frankly that may be insurmountable limitations of the precision of `double`. – Louis Wasserman May 16 '16 at 21:29
  • Possible duplicate of [How many significant digits have floats and doubles in java?](http://stackoverflow.com/questions/13542944/how-many-significant-digits-have-floats-and-doubles-in-java) – RaminS May 16 '16 at 21:34
  • and you forgot your timer of reposting questions at one hour http://stackoverflow.com/questions/37263350/using-taylor-series-to-calculating-pi-and-figure-out-the-term-to-use – gpasch May 17 '16 at 01:29

2 Answers2

0

As Louis Wasserman suggested you are running into precision limitations with doubles in Java. Consider using BigDecimals for your calculations for more precision.

Barry
  • 237
  • 1
  • 2
  • 11
0

The floating-point errors in your sum are adding up to that difference, simply reverse your iteration (t = 31..2, i.e. start by adding up the very small summands first) and the error goes away:

public static double compPiReversed()
{
    int terms1 = 31;
    int sg = -1;
    double sum = 0;
    for (int t = terms1; t >= 2; --t) {
        int denom1 = 1 + (t-1) * 2;
        double denom2 = Math.pow(3, t-1);
        double term = 1.0 / (denom1 * denom2);
        sg *= -1;
        sum += sg * term;
    }
    sum += 1;
    double pi = Math.sqrt(12) * sum;
    return pi;
}

again the 31st summand won't actually contribute (try starting at terms1 = 30, don't forget to change the sign sg = 1, too.)

BeyelerStudios
  • 4,243
  • 19
  • 38