在Python中使用整数除法时,我可以保持小数精度吗



当我除以2/3时,得到0.66666666,当我除以2//3时,得到0。

有没有办法在保留小数点的同时计算整数除法?

编辑:看起来我可能已经把你们很多人弄糊涂了,我的坏。因此,我的教授告诉我,由于标准除法(2/3)最多只能返回0.666666666666个数字,所以当我想进行小数点后需要超过203个数字的计算时,这是没有用的。我想知道是否有一种方法可以做2//3(会返回0),但不知怎么的,最终仍然是.6666

对于某些有限的小数,可以使用Python的float.as_integer_ratio()方法:

>>> 0.5.as_integer_ratio()
(1, 2)

对于2/3,它不能完全用十进制表示,这开始给出不太理想的结果:

>>> (2/3).as_integer_ratio()
(6004799503160661, 9007199254740992)      # approximation of 2/3

对于有理数的任意精度,请使用Python库中的分数:

>>> import fractions
>>> fractions.Fraction('2/3')
Fraction(2, 3)
>>> Frac=fractions.Fraction
>>> Frac('2/3') + Frac('1/3') + Frac('1/10')
Fraction(11, 10)
>>> Frac('2/3') + Frac('1/6') + Frac('1/10')
Fraction(14, 15)

然后,如果你想用十进制更准确地表示,可以使用decimal库将整数分子和分母转换为任意精度的十进制:

>>> f=Frac('2/3') + Frac('1/6') + Frac('1/10')
>>> f
Fraction(14, 15)
>>> f.numerator
14
>>> f.denominator
15
>>> import decimal
>>> decimal.Decimal(f.numerator) / decimal.Decimal(f.denominator)
Decimal('0.9333333333333333333333333333')

您也可以在除法前将一个整数强制转换为浮点值。

In [1]: float(2)/3
Out[1]: 0.6666666666666666

这将防止整数截断,并将结果作为float

也许看看decimal.Decimal():

>>> import decimal
>>> x = decimal.Decimal(2/3)
>>> x
Decimal('0.66666666666666662965923251249478198587894439697265625')

//是一个floor除法,它会给你整数floor的结果。无论您使用2//3还是float(2)//3。使用//时无法保持精度。

在我的环境(python2.7.6)中,2//3返回0float(2)//3返回0.0,两者都不能保持精度。

一个类似的问题也许对你有帮助。

这不是对您问题的直接回答,但它将帮助您了解udnerstand

我发布了两个链接,其中解释了有关实现的许多细节:

  • 来自Guido的python历史博客:
  • 自PEP-0238

以下是我们需要注意的事项:

>>> 2/3
0
>>> 2/3.0
0.6666666666666666
>>> 2//3
0
>>> -2//3
-1
>>>

来自PEP-0238

当前的除法(/)运算符对数字参数:它返回数学的底线除法的结果,如果参数是int或long,但它如果自变量是浮动的或复杂的。这使得表达式期望浮点或复杂结果当整数不是预期但可能作为输入。

我们建议通过引入不同的运营商来解决这个问题不同的操作:x/y返回的合理近似值除法的数学结果("真除法"),x//y到返回楼层("楼层划分")。我们把电流称为混合x/y"经典除法"的含义。-在Python 2.x中,经典分割将保持为默认分割系列真正的除法将是Python 3.0中的标准。

- The // operator will be available to request floor division
unambiguously.
- The future division statement, spelled "from __future__ import
division", will change the / operator to mean true division
throughout the module.
- A command line option will enable run-time warnings for classic
division applied to int or long arguments; another command line
option will make true division the default.
- The standard library will use the future division statement and
the // operator when appropriate, so as to completely avoid
classic division.

最新更新