Can someone help me in understanding how to use these rational, numerator & denominator
*class numbers.Rational Subtypes Real and adds numerator and denominator properties, which should be in lowest terms. With these, it provides a default for float().
numerator Abstract.
denominator Abstract.*
Here's the link to the official documentation
The numbers
module provides some abstract base classes that you can use if you are implementing your own numeric types. You don't need to use them, but they offer some help in getting things right, if you want it.
They're not builtin types that you can always access, those are different. The concrete numeric types in Python are int
, float
, complex
and, if you're willing to go into the standard library, fractions.Fraction
and decimal.Decimal
.
In the interactive session you show in the question, you're creating a complex
object and a float
(by dividing integers). These are not the same thing as numbers.Complex
or numbers.Rational
. And while the numbers.Complex
class's API is a close match to how the concrete complex
type actually works, the float
type is much more different from the abstract numbers.Rational
API.
If you just want to represent a float
as a fraction, try calling the as_integer_ratio()
method on it. This may not be the fraction you expect! That's because floating point values are not always exact, especially when a binary representation was infinitely repeating and needed to be truncated somewhere.