为什么Python中的float对象没有denominator属性,而int呢?

Rad*_*ian 5 python floating-point int types

虽然我在搞乱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']
Run Code Online (Sandbox Code Playgroud)

虽然我理解'共轭','成像'和'真实'是为了与复杂类型兼容,但我不明白为什么'分子'和'分母'只存在于int中,而不是为了一个浮子.

对此有何解释?

Gor*_*ley 5

这很可能是因为花车有点有损 - 它们不能完美地代表每一个价值.考虑这个例子:

>>> 1.0/5.0
0.20000000000000001
Run Code Online (Sandbox Code Playgroud)

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


Dan*_*son 5

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

numbers.Integral 是一个子类 numbers.Rational

它是数字.Rational添加分子和分母成员.