Question

The following code gives me no error, yet it does not calculate Pi correctly. Please take a look and see if you can find out what I'm doing wrong.

Main method:

public static void main(String [] args){

    Pi obj1=new Pi();
    System.out.println("The answer is: " + obj1.calculatePi(20));
}

calculatePi method:

public  BigDecimal calculatePi (int iterations) { 
    BigDecimal result = new BigDecimal(0);    // The result (summation of Taylor series)    
    BigDecimal nextTerm= new BigDecimal(0);
    BigDecimal j= new BigDecimal(2);
    BigDecimal i= new BigDecimal(4);
    BigDecimal num= new BigDecimal(16);
    BigDecimal oddNum = new BigDecimal(1);    // Odd numbers (1, 3, 5, 7 etc.)     
    BigDecimal pow5 = new BigDecimal(5);      // Odd powers of 5 (5^1, 5^3, 5^5 etc.)     
    BigDecimal pow239 =new BigDecimal(239);  // Odd powers of 239 (239^1, 239^3, 239^5 etc.)    
    BigDecimal sign = new BigDecimal(1);      // Either 1 or -1 indicating the sign of the next term              
    for (int count = 0; count < iterations; count++) {         // Calculate and add the next term in the series. 
        // The sign of each new term alternates.        
        nextTerm = num.divide (pow5.multiply( oddNum),100,BigDecimal.ROUND_HALF_UP).subtract (i.divide (pow239.multiply( oddNum),100, BigDecimal.ROUND_HALF_UP)); 
        result= sign.multiply(nextTerm).add(result);                      // Update variables for next time around loop        
        pow5 = pow5.multiply(pow5).multiply(pow5);        
        pow239 = pow239.multiply(pow239).multiply(pow239);        
        oddNum= oddNum.add(j);         
        sign = sign.subtract(sign);     }
    return result;  
}
Était-ce utile?

La solution 2

You aren't getting a result because your program is still running. Think about the size of the numbers you are calculating there in that method. 11 iterations is a stretch on my machine, 20 is probably far outside the reach of a common PC. Try running 5 iterations and optimizing your algorithm before going higher again.

Aside from that, lejlot is correct, you should negate the sign, not just substract it from one iteration to the next.

Edit: For 10 iterations I get the following result: Pi: 3.140598667726060313997433309223757530269291966682082323...

Since we all know from memory that Pi starts out as 3.14159265358979323846264... that's not all that accurate yet.

Autres conseils

One of the errors that are visible here, is thatsign is supposed to alternate between -1 and 1, and yours becomes 0 in second iteration

sign = sign.subtract(sign);   

it starts with 1,so

sign = 1 - 1 // == 0

it should be

sign = sign.negate();   
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top