Why don't floating objects in Python have a denominator attribute, and int -?

While I was working with 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']

Although I understand that “conjugation”, “imagination” and “reality” exist for compatibility with a complex type, I can’t understand why the “numerator” and “denominator” exist only for int, and don’t for float.

Any explanation for this?

+5
source share
3 answers

This is most likely because the floats are somewhat lost - they cannot perfectly represent each value. Consider this example:

>>> 1.0/5.0
0.20000000000000001

, 1.0/5.0 python 18014398509481984 (20000000000000001/100000000000000000 == 3602879701896397/18014398509481984). , python , , .

+5

: Python

numbers.Integral numbers.Rational

number.Rational, .

+5

This is because it intis a subclass rational, but floatnot. Since it rationalhas the denominator attribute, intinherited it.

You can read here

+2
source

All Articles