2014-10-28 66 views
1

今天我一直在玩BigDecimal,並以下面的代碼結束。根據我的編譯器,沒有問題,但運行後我有一些例外。任何幫助表示讚賞,非常感謝你:-)使用BigDecimal打印Pi:代碼效率低下並且不起作用

import java.math.*; 
//Ramanujan's Method of Calculating Pi 
public class Main{ 

//a1-4 are constants used in side calculations 
private static final BigDecimal a1 = new BigDecimal(9810); 
private static final BigDecimal a2 = new BigDecimal(1103); 
private static final BigDecimal a3 = new BigDecimal(26390.0); 
private static final BigDecimal a4 = new BigDecimal(396.0); 

//con1 is accurate repersentation of 2sqrt(2) 
private static final BigDecimal con1 = BigDecimal.valueOf(2*Math.pow(2,-1)); 

//with increase in size of var loops, leads to more accurate output of Pi 
private static final BigDecimal loops = new BigDecimal(2); 

//Asum = 1/pi later in program 
private static BigDecimal asum; 

//fouri = 4... May not need this 
private static BigDecimal fouri = new BigDecimal(4); 

//Factorial :: n * n-1 * n-2 ... * 1 
public static BigDecimal factorial(BigDecimal n){ 
    if(grt(n, BigDecimal.ZERO)) return BigDecimal.ONE; 
    return n.multiply(factorial(n.subtract(BigDecimal.ONE))); 
} 

//calc0-4 exist for increased readibility in main calculation 
public static BigDecimal calc0(){ 
    return con1.divide(a1, loops.intValue()*16, BigDecimal.ROUND_HALF_DOWN); 
} 

public static BigDecimal calc1(BigDecimal i){ 
    BigDecimal ret; 
    ret = (factorial(fouri.multiply(i))); 
    return ret; 
} 

public static BigDecimal calc2(BigDecimal i){ 
    return (a2.add(a3.multiply(i))); 
} 

public static BigDecimal calc3(BigDecimal i){ 
    BigDecimal ret = new BigDecimal(Math.pow(factorial(i).doubleValue(), 4)); 
    return ret; 
} 

public static BigDecimal calc4(BigDecimal i){ 
    BigDecimal ret = new BigDecimal(Math.pow(a4.doubleValue(),(i.doubleValue() * 4))); 
    return ret; 
} 


//Compares two BigDecimals and returns true if i <= a 
public static boolean grt(BigDecimal i, BigDecimal a){ 
    BigDecimal b = new BigDecimal(a.compareTo(i)); 
    if(b.equals(BigDecimal.ZERO)||b.equals(BigDecimal.ONE)) return true; 
    return false; 
} 

public static void main(String []args){ 
    //Main calculation-- 
    for(BigDecimal i = new BigDecimal(0);grt(i,loops);i.add(i.ONE)){ 
     asum = asum.add(calc0().multiply(calc1(i)).multiply(calc2(i)).divide(calc3(i),loops.intValue()*16, BigDecimal.ROUND_HALF_DOWN).multiply(calc4(i))); 
    } 
    //Prints Pi 
    System.out.println(asum.pow(-1)); 
} 

}

回答

1

這裏asumnull

private static BigDecimal asum; // not initialize 

然後

for(BigDecimal i = new BigDecimal(0);grt(i,loops);i.add(i.ONE)){ 
    asum = asum.add(//rest of the code); // you will get NullPointerException 
} 

解決方案

初始化asum

private static BigDecimal asum=new BigDecimal(0);  
+0

感謝:-)我的代碼現在正在運行,但我還沒有它打印出任何東西。也許它試圖佔用太多內存? – BlurryZombie 2014-10-28 05:52:34