因此,在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()
并没有改变任何事情。该错误显然是由于某个时刻出现非法角色造成的。我猜它可能是一个记忆错误,虽然我不确定。
您可以尝试为代码设置一个断点,并尝试深入研究它。
这是引擎盖下会发生的事情。
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
BR,
蒂姆