英文:
Why pow() function in python and pow() function in dart produces different result for same input?
问题
我想在Dart语言中评估pow(17,18)
,但它产生了6665467901046659617
。在Python语言中,相同的表达式pow(17,18)
产生了14063084452067724991009
。
我也想在Dart中实现相同的结果。
英文:
I want to evaluate pow(17,18)
in Dart language, but it produces 6665467901046659617
. In Python language the same expression pow(17,18)
produces 14063084452067724991009
.
I want to achieve the same result in Dart also.
答案1
得分: 4
看起来Dart在某个时候出现了溢出问题,与Python不同,它不支持任意大的整数。
你可能正在使用Dart 2,它对整数有一个64位的限制。对于这个大小,最大整数是9,223,372,036,854,775,807。Dart 1有一个类似Python的整数数学实现,允许任意大小的整数(仅受可用内存限制)。
因此,你看到的值6,665,467,901,046,659,617,只是pow(17,18)
对Dart 2的最大整数值取模后的结果+1。
然而,Dart 2仍然有BigInt,专门用于此目的。如用户@mmcdon20在评论中指出,你正在寻找的是:
BigInt.from(17).pow(18)
英文:
It looks like Dart runs into an overflow at some point and does not (like Python) support arbitrarily large integers.
You are likely using Dart 2, which has a limit of 64 bits for integers. The maxint for that size is 9,223,372,036,854,775,807. Dart 1 did have a similar integer math implementation to Python, allowing integers of arbitrary size (limited by available memory only).
So, it makes sense that you're seeing a value like 6,665,467,901,046,659,617, which is just the result of pow(17,18)
modulo the maximum integer value for Dart 2 + 1.
However, Dart 2 still has BigInt, exactly for this purpose. As user @mmcdon20 indicated in the comments, you're looking for:
BigInt.from(17).pow(18)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论