using bigdecimal class
I was using Gregory-Leibniz series to calculate PI = 4 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + ...
Something like:
double pi = 0.0;
int limit = 3000000;
for (int i = 0, y = 1; i <= limit; y+=2, i++)
{
if (y == 1)
pi = 4;
elseif (i % 2 == 0)
pi += (double)4/y;
else
pi -= (double)4/y;
System.out.println(String.format("Loop %d: %.20f", i, pi));}
Then I realized PI isn't going to be totally accurate according to IEEE Standard for Binary Floating-Point Arithmetic that java math calculation uses, so I was trying to use BigDecimal class (new to me), this is what I got initally...
BigDecimal pi =new BigDecimal("0.00");
int limit = 3000000;
for (int i = 0, y = 1; i <= limit; y += 2, i++)
{
if (y == 1)
pi =new BigDecimal("4.0");
elseif (i % 2 == 0)
pi = pi.add(new BigDecimal( Double.toString( (double) 4 / y )));
else
pi = pi.subtract(new BigDecimal( Double.toString( (double) 4 / y )));
System.out.println(String.format("Loop %d: %s", i, pi.toString()));
}
I realize that when I do the 4/y calculations involving both doubles... the result is probably stored according to the IEEE standards which is the thing to avoid... Is that correct? Is my PI result going to be accurate?
I noticed with this one decimals up to the 22nd place are all filled with some numbers in the calculations compared with the first one involving only double number calculations which had zero's starting around the 15th decimal.
Something like doesn't work and ends up with arithmeticexceptions...
pi = pi.subtract(new BigDecimal("4").divide(new BigDecimal(Integer.toString(y))));
So I'm actually confused about the right way of using BigDecimal class in this type of calculation to get accurate results. I do realize it's an immutable class and probably a bad idea to use it like this 3 million times in a loop.

