2017-04-30 80 views
0

我正在计算浮点数的总和。所有小数字都输出正确,当我使用非常大的数字作为输入时,输出总是由几个整数关闭。例如,H = 5764801 W = 1679616,在纸上,计算结果为335923 。在我的程序中,代替打印335923 。下面是代码:浮标精度损失

public void printOutput(int H, int W) // The inputs 
{ 
    if(H == 1 && W == 1) 
    { 
     System.out.println(0 + " " + 1); 
     return; 
    } 

    List<Integer> pfw = primeFactors(W); 

    int y = 1; 

    while(H != (int) (Math.pow(Math.pow(W, 1f/y) + 1f, y))) y++; 

    final float N = findWholeNumber(pfw); 

    float height = 0; 
    for(int x = 1; x <= y + 1; x++) 
    { 
     height += (float) (W * Math.pow((N + 1f)/N, x-1f) + 1e-8); //Here is the summation 
    } 
    float cats = 1; 
    for(int x = 2; x <= y + 1; x++) 
     cats += (float) (Math.pow(N, x-1)); 

    int notWorking = (int) (cats - W); 
    System.out.println(notWorking + " " + (int)height); //Outputs printing 
} 

private int findWholeNumber(List<Integer> factors) 
{ 
    List<Integer> common = new ArrayList<Integer>(); 
    for(int i = 0; i < factors.size(); i++) 
    { 
     if(common.contains(factors.get(i))) continue; 
     common.add(factors.get(i)); 
    } 
    int num = common.get(0); 
    for(int i = 1; i < common.size(); i++) 
     num *= common.get(i); 
    return num; 
} 

private List<Integer> primeFactors(int num) 
{ 
    List<Integer> pf = new ArrayList<Integer>(); 

    if(num == 1) 
    { 
     pf.add(1); 
     return pf; 
    } 

    for(int j = 2; j <= num; j++) 
     while(num % j == 0) // is prime 
     { 
      pf.add(j); 
      num /= j; 
     } 

    return pf; 
} 

}

+0

任何理由不使用'double'? –

回答

2

浮点数具有有限的精度作为尾数具有有限的宽度。

你可以尝试double您的情况,精度更高(因为它的尾数更宽),但它也是有限的。

的更多信息:https://en.wikipedia.org/wiki/IEEE_floating_point#IEEE_754-2008What is the maximum number in the mantissa part of a Java float?

如果你需要有一个具有无限精度,尽量BigDecimal。有效位数的计数仅受存储器数量的限制。

如果您只需要整数值,BigInteger是一个选项。