2

I have started a java project for computing the n-th digit of pi, and decided to use the BBP algorithm. In my output (in another class) I have been getting some weird math errors, and I don't know where it is from. So, I don't think I am putting the algorithm in the code correctly.

I got the algorithm from http://en.wikipedia.org/wiki/Bailey%E2%80%93Borwein%E2%80%93Plouffe_formula

Here's my code:

import java.lang.Math;
import java.lang.Math.*;
public class Pi
{
public static double getDigit(int n, int infinity)
{   int pow = 0;
    double[] sums = new double[4];
    int tot = 0;
    int result = 0;
    double fraction = 0;
    for(int x = 0; x < 4; x++)
    {
        for(int k = 0; k < n; k++)
        {
            tot = 8 * k + 1;
            if(x == 1)
                tot += 3;
            else if(x > 1)
                tot++;
            pow = n-k;
            result = modular_pow(16, pow, tot);
            sums[x] += (double)result / (double)tot;
        }
        for(int i = n + 1; i < infinity; i++)
        {
            tot = 8 * i + 1;
            if(x == 1)
                tot += 3;
            else if(x > 1)
                tot++;
            fraction = Math.pow(16.0, (double)pow);
            sums[x] += fraction / (double)tot;
        }
    }
    return 4 * sums[0] - 2 * sums[1] - sums[2] - sums[3];
}
public static int modular_pow(int base, int exponent, int modulus)
    {
    int result = 1;
    while(exponent > 0)
    {
        if (exponent % 2 == 1)
            result = (result * base) % modulus;
        exponent--;
        base = (base * base) % modulus;
    }
    return result;
}

Thanks in advance.

  • 1
    You probably shouldn't be using `double`s for that. They have only 53 bits of precision. You might try using `BigDecimal` instead if you aren't doing too much arithmetic. – tmyklebu Apr 11 '13 at 04:21
  • The errors are large, so using BigDecimal would only change it a little. – user2268648 Apr 11 '13 at 13:52
  • BBP is, AFAIK, a spigot algorithm, so it should be doable with only integers and BigDecimal, the latter only for the higher precision division. BBP delivers 16 bit digits, though. – Rudy Velthuis Jan 11 '16 at 17:02

1 Answers1

1

Firstly, apologies for necro-ing an old post, but there is a severe lack of explanation of the BBP algorithm being applied meaningfully and so I think this might still be useful to some people who want to look into it.

Based on the Wikipedia article, the result you're returning needs to be stripped of its integer part (leaving the fractional part) and then multiplied by 16. This should leave the integer part as a representation of the nth hex digit of pi. I'll test it out tomorrow and see if that helps. Otherwise, great implementation, easy to understand and efficiently done.