I'm trying to calculate digits of pi in java using the Chudnovsky algorithm. I'm using BigDecimal to be as precise as possible, but the formula is for 1/pi. I want to convert the value that I find to pi/1. I tried using Math.pow() and BigDecimal.pow() but couldn't figure it out. What would be the best way to find the reciprocal of a BigDecimal? Here's my code:
public static void main(String[] args)
{
JFrame j = new JFrame("Pi");
j.setSize(300,100);
j.setVisible(true);
JTextArea jt = new JTextArea();
Container contain = new Container();
FastPi fp = new FastPi();
BigDecimal pi = new BigDecimal(0);
for(long l=0; l<Long.MAX_VALUE; l++)
{
pi = BigDecimal.valueOf(12*(((Math.pow(-1,l)*fp.factorial(6*l)*
(545140134*l+13591409))/
(fp.factorial(3*l)*
Math.pow(fp.factorial(l),3)*
Math.pow(640320,3*l+3/2)))));
contain = j.getContentPane();
// tried to do pi^-1 below this comment
jt.setText(String.valueOf(pi.pow(-1)) + " " + l);
contain.add(jt);
}
}
public long factorial(long f)
{
long result = 1;
for(int i=2; i<=f; i++)
{
result *= i;
}
return result;
}
Sorry I used L as a variable, it's colored different than the 1 though.
Divide 1
by your algorithm's result, preserving the scale of your result:
BigDecimal inversePi = yourAlgorithm();
BigDecimal pi = BigDecimal.ONE.divide(inversePi, inversePi.scale(), RoundingMode.HALF_UP);