【问题标题】:Groovy throws Numberformatexception when dealing with extremely large numbersGroovy 在处理非常大的数字时抛出 Numberformatexception
【发布时间】:2018-06-24 21:06:48
【问题描述】:

所以在 Intellij IDEA 中使用 groovy,我使用以下代码得到一个异常:

def t = (100000G**100000000000G)

现在我知道这些是任何理智的人都不会想要计算的数字,但出于询问的目的,出于我的好奇心,为什么会引发以下异常?

Exception in thread "main" java.lang.NumberFormatException
at java.math.BigDecimal.<init>(BigDecimal.java:494)
at java.math.BigDecimal.<init>(BigDecimal.java:383)
at java.math.BigDecimal.<init>(BigDecimal.java:806)
at java.math.BigDecimal.valueOf(BigDecimal.java:1274)
at org.codehaus.groovy.runtime.DefaultGroovyMethods.power(DefaultGroovyMethods.java:14303)
at org.codehaus.groovy.runtime.dgm$489.invoke(Unknown Source)
at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoMetaMethodSiteNoUnwrapNoCoerce.invoke(PojoMetaMethodSite.java:274)
at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite.call(PojoMetaMethodSite.java:56)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:128)
at dev.folling.code.Main.main(Main.groovy:11)

** 替换为.power() 并不会改变它的任何内容。 该错误显然是由于某个时候出现的非法字符引起的。虽然我不确定,但我怀疑这可能是内存错误。

【问题讨论】:

    标签: math groovy numberformatexception bignum


    【解决方案1】:

    您可以尝试为您的代码设置一个断点,然后尝试深入研究它。

    这就是幕后发生的事情。

    public static BigInteger power(BigInteger self, BigInteger exponent) {
        return exponent.signum() >= 0 && exponent.compareTo(BI_INT_MAX) <= 0?self.pow(exponent.intValue()):BigDecimal.valueOf(Math.pow(self.doubleValue(), exponent.doubleValue())).toBigInteger();
    }
    

    在正在运行的进程中,它通过以下代码返回“Infinity”:

    Math.pow(self.doubleValue(), exponent.doubleValue())
    

    然后 BigDecimal 将使用 valueof 将其转换为 BigInteger

    BigDecimal.valueOf("Infinity")
    

    这就是为什么您会收到 NumberFormatException

    兄弟,

    提姆

    【讨论】:

    • 有趣,虽然我预料到了,但我不知道 BigInteger/BigDecimals 有“Infinity”之类的东西
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-01
    • 2013-08-05
    • 2010-10-07
    • 2015-11-06
    • 2013-07-24
    相关资源
    最近更新 更多