【问题标题】:Why float objects in Python doesn't have denominator attribute, while int does?为什么 Python 中的 float 对象没有 denominator 属性,而 int 有?
【发布时间】:2023-04-10 12:28:01
【问题描述】:

当我在玩 Python 时,

>>> [attr for attr in dir(1) if not attr.startswith('_')]
['bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real']
>>> [attr for attr in dir(1.1) if not attr.startswith('_')]
['as_integer_ratio', 'conjugate', 'fromhex', 'hex', 'imag', 'is_integer', 'real']

虽然我知道'conjugate'、'imag'和'real'是为了与复杂类型兼容,但我不明白为什么'numerator'和'denominator'只存在于int,而不是不是为了花车。

对此有何解释?

【问题讨论】:

  • 您希望math.pi.denominator 返回什么?
  • 我会说 7,但在 Wikipedia-ing 之后,我了解到 pi 是无理数,并不完全等于有理数的 22/7。

标签: python types floating-point int


【解决方案1】:

这很可能是因为浮点数有些有损——它们不能完美地表示每个值。考虑这个例子:

>>> 1.0/5.0
0.20000000000000001

如果你想要访问1.0/5.0 python 的分母必须返回18014398509481984 (20000000000000001/100000000000000000 == 3602879701896397/18014398509481984)。精度的损失会导致python别无选择,只能返回疯狂的值,所以设计者选择不实现该功能。

【讨论】:

  • 你的意思是3602879701896397/18014398509481984
【解决方案2】:

看一下数字类层次结构:Python numbers

numbers.Integralnumbers.Rational 的子类

它是数字。添加分子和分母成员的有理数。

【讨论】:

    【解决方案3】:

    这是因为intrational 的子类,而float 不是。由于rational有分母属性,所以int继承了它。

    您可以阅读更多here

    【讨论】:

      猜你喜欢
      • 2015-05-23
      • 2015-03-28
      • 2018-10-22
      • 2018-10-02
      • 2013-11-05
      • 1970-01-01
      • 2015-04-25
      • 1970-01-01
      • 2016-12-02
      相关资源
      最近更新 更多