Question

I have to calculate PI to a certain number of decimals (given in variable zecimale), using the Leibniz formula for calculating PI. I don't know why, but not a single addition or subtraction on that BigDecimal isn't modifying the value of PI.

Why is this?

int zecimale = 0;

if (args.length > 0) {
    try {
        zecimale = Integer.parseInt(args[0]);
    } catch (NumberFormatException e) {
        System.err.println("Argument" + " must be an integer");
        System.exit(1);
    }
}

long start = System.nanoTime();
double numitor = 1;
BigDecimal numitor1 = new BigDecimal(1/numitor); 

BigDecimal pi = new BigDecimal(1);

for(int x = 0; pi.scale() <= zecimale; x++)
{
    numitor1 = new BigDecimal(1 / numitor);

    if(x % 2 == 0)
    {
       pi.add(numitor1);
    }
    else
    {
       pi.subtract(numitor1);
    }
    BigDecimal doi = new BigDecimal(2);
    numitor = numitor + 2;

    System.out.println(x);
    System.out.println(pi);
}
BigDecimal patru;
patru = new BigDecimal(4);
pi.multiply(patru);

No correct solution

OTHER TIPS

BigDecimal is immutable so the is no way to change it's value. (In the same way String does) This is why all the methods would operate on a BigDecimal return a new BigDecimal as the result

e.g.

 pi = pi.add(numitor1);

The second problem is you are using a double in your calculation, defeating the whole point of using a BigDecimal.

The expression pi.scale() should be ~53 after the first iteration and won't get much higher the way ti is written. scale only tells you how many decimal places there are after the dot, not the accuracy of the solution.

You will get better performance if you calculate two expressions in a single loop.

The last problem you have is that each digit takes 10x longer to evaluate, calculating mroe than 15 digits (more than the precision you can get with double) it will take years to complete.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top