Sreeragh A R
Sreeragh A R

Reputation: 3021

How to compare Fraction objects in Python?

I have a use case of equating fractions. Found fractions module in Python.

Tried using operators like <, == and > and it seems working.

from fractions import Fraction
print(Fraction(5,2) == Fraction(10,4)) # returns True
print(Fraction(1,3) > Fraction(2, 3))  # return False

Is this the expected way of doing comparisons?

Could not find anything explicitly specified in the docs.

Can someone confirm this (with a link to the source where it is mentioned)?

Upvotes: 1

Views: 2346

Answers (2)

Fred Larson
Fred Larson

Reputation: 62093

Note from the documentation of Fraction that "The Fraction class inherits from the abstract base class numbers.Rational, and implements all of the methods and operations from that class."

Looking at the documentation of Rational, we find that it "Subtypes Real and adds numerator and denominator properties, which should be in lowest terms."

For Real, we find:

To Complex, Real adds the operations that work on real numbers.

In short, those are: a conversion to float, math.trunc(), round(), math.floor(), math.ceil(), divmod(), //, %, <, <=, >, and >=.

And finally Complex:

Subclasses of this type describe complex numbers and include the operations that work on the built-in complex type. These are: conversions to complex and bool, real, imag, +, -, *, /, abs(), conjugate(), ==, and !=. All except - and != are abstract.

So yes, these operations are defined and documented.

Upvotes: 2

prvnsmpth
prvnsmpth

Reputation: 315

Looking at the implementation of the fraction module, we can see that __eq__ is defined:

def __eq__(a, b):
    """a == b"""
    if type(b) is int:
        return a._numerator == b and a._denominator == 1
    if isinstance(b, numbers.Rational):
        return (a._numerator == b.numerator and
                a._denominator == b.denominator)
    ...

And so are __lt__ and __gt__:

def __lt__(a, b):
    """a < b"""
    return a._richcmp(b, operator.lt)

def __gt__(a, b):
    """a > b"""
    return a._richcmp(b, operator.gt)

So the == and </> operators will work as expected.

Upvotes: 1

Related Questions