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.