楼层功能正在消除整数科学记法,Python

时间:2017-06-13 18:12:25

标签: python python-3.x scientific-notation approximation

我将通过示例解释我的问题:

>>> #In this case, I get unwanted result
>>> k = 20685671025767659927959422028 / 2580360422
>>> k
8.016582043889239e+18
>>> math.floor(k)
8016582043889239040
>>> #I dont want this to happen ^^, let it remain 8.016582043889239e+18
>>> #The following case though, is fine
>>> k2 = 5/6
>>> k2
0.8333333333333334
>>> math.floor(k2)
0

如何使math.floor不对科学记号进行拼写?是否有一个规则,用科学记数法表示数字(我想这将是一定的边界)。

修改

我首先认为math.floor函数导致了精度损失,但事实证明第一次计算本身失去了计算的准确性,这让我很困惑,可以在这里轻松看到:

>>> 20685671025767659927959422028 / 2580360422
8016582043889239040
>>> 8016582043889239040 * 2580360422
20685671025767659370513274880
>>> 20685671025767659927959422028 - 20685671025767659370513274880
557446147148
>>> 557446147148 / 2580360422
216.0342184739958
>>> ##this is >1, meaning I lost quite a bit of information, and it was not due to the flooring

所以现在我的问题是如何获得除法的实际结果。我看了下面的帖子: How to print all digits of a large number in python? 但出于某种原因,我没有得到相同的结果。

修改 我在这里找到了一个简单的分割精度问题解决方案: How to manage division of huge numbers in Python? 显然//运算符返回int而不是float,它与机器的内存没有大小限制。

1 个答案:

答案 0 :(得分:3)

在Python 3中,math.floor返回一个整数。使用科学记数法不显示整数。一些浮点数 使用科学记数法表示。如果你想要科学记数法,试着转回浮动。

>>> float(math.floor(20685671025767659927959422028 / 2580360422))
8.016582043889239e+18

正如Tadhg McDonald-Jensen指出的那样,您也可以使用str.format以科学记数法获取整数的字符串表示形式:

>>> k = 20685671025767659927959422028 / 2580360422
>>> "{:e}".format(k)
'8.016582e+18'
事实上,这可能比转换为浮动更实用。作为一般经验法则,您应该根据所需的精度和范围选择数值数据类型,而不必担心打印时的样子。