你什么时候使用对象BigInteger而不是简单地使用double?

时间:2015-11-02 07:15:52

标签: java

因此我遇到了一个问题,告诉我要制作一个最大为30的整数阶乘表。这本书特别告诉我使用BigInteger这个对象。 (使用BigInteger big = BigInteger.valueOf(x))但是这样做非常棘手并且给了我一堆错误,我不知道如何修复。

例如

public static BigInteger factorial(int a){
        if(a == 0){
            return BigInteger.valueOf(1);
        }
        else{
            return BigInteger.valueOf(a*BigInteger.valueOf(factorial(a-1)));// this will keep giving me an error message that I need to change the value type to "long" and back and forth to BIgInteger.  I've tried many different variations including where I use BigInteger.valueOf(..) to every values.
        }

    }  

您是否知道使用BigInteger对象的正确方法?

你什么时候会使用BigInteger而不是double?

   import java.math.BigInteger;
        public class BigInt {

            public static double factorial(int a){
                if(a == 0){
                    return 1;
                }
                else{
                    return a* factorial(a-1);
                }

            }
            public static void table(int a){
                for(int i =0; i<=a; i++){
                    System.out.println(i + ", " + factorial(i) );

                    }
                }

            public static void main(String[] args) {
            table(30);
            }

        }

5 个答案:

答案 0 :(得分:1)

而不是

BigInteger.valueOf(a*BigInteger.valueOf(factorial(a-1)))

factorial(a - 1).multiply(BigInteger.valueOf(a))

您目前正在尝试使用*运算符乘以intBigInteger;这是Java中不允许的,因为不支持运算符重载。

至于为何使用BigInteger代替doubledouble在开始四舍五入之前仅支持有限数量的有效数字。使用BigInteger可以让您拥有任意大的数字。

答案 1 :(得分:1)

当您使用BigInteger时,您无法使用*等运算符。您必须使用BigInteger类的方法:

return factorial(a-1).multiply(a);

使用BigInteger代替double的原因是精确度。 double精度有限,因此无法准确表示大整数。

编辑:您应该实际使用

return BigInteger.valueOf(a).multiply(factorial(a-1));

因为BigInteger multiply(long v)是包私有。

答案 2 :(得分:0)

它不是原始类型所以*不起作用。 有关详细说明,请阅读本文,关于使用对象BigInteger的简要说明。我希望它能帮到你很多。 Java:Why should we use BigDecimal instead of Double in the real world?

答案 3 :(得分:0)

当我们处理与货币相关的数字时,我们需要以最接近的精度得到结果。然后我们使用BigInteger而不是double。但与double相比,Big Integer的性能较慢,因为内部BigInteger需要更多的运算符进行处理。我建议使用javadoc(http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigDecimal.html)。

答案 4 :(得分:0)

使用大整数进行数值计算时,使用BigInteger也是必要的。加密目的。在浮点数或双打数上使用的舍入将使得应用这些加密方法的理论变得不可能。

相关问题