Skip to content

Instantly share code, notes, and snippets.

@rarylson
Last active July 9, 2016 03:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rarylson/3ce80c23d77a86b298eb7fe635e50888 to your computer and use it in GitHub Desktop.
Save rarylson/3ce80c23d77a86b298eb7fe635e50888 to your computer and use it in GitHub Desktop.
A class that represents a rational number (useful for study purposes)
""" Module for working with fractional/rational numbers
"""
from functools import total_ordering
def gcd(a, b):
""" Greast common divisor between two numbers
It uses the Euclidean algorithm.
"""
while b:
a, b = b, a % b
return a
@total_ordering
class Rational(object):
""" A rational number
It represents a number in the form a / b (Rational(a, b)).
"""
def __init__(self, num, den=1):
if type(num) != int or type(den) != int:
raise ValueError(
"The numerator and the denominator must be integers.")
if den == 0:
raise ZeroDivisionError(
"The denominator should be different of zero")
self.num = num
self.den = den
self.__simplify()
def __repr__(self):
return "Rational({0}, {1})".format(self.num, self.den)
def __simplify(self):
factor = gcd(self.num, self.den)
self.num = self.num // factor
self.den = self.den // factor
def __lt__(self, other):
if not isinstance(other, Rational):
raise NotImplemented
return self.num * other.den < self.den * other.num
def __eq__(self, other):
if not isinstance(other, Rational):
raise NotImplemented
return self.num * other.den == self.den * other.num
def __add__(self, other):
if not isinstance(other, Rational):
raise NotImplemented
return Rational(
self.num * other.den + self.den * other.num,
self.den * other.den)
def __neg__(self):
return Rational(- self.num, self.den)
def __sub__(self, other):
if not isinstance(other, Rational):
raise NotImplemented
return self + (- other)
def __mul__(self, other):
if not isinstance(other, Rational):
raise NotImplemented
return Rational(self.num * other.num, self.den * other.den)
def __invert__(self):
return Rational(self.den, self.num)
def __div__(self, other):
if not isinstance(other, Rational):
raise NotImplemented
return self * (~ other)
def __truediv__(self, other):
return self.__div__(other)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment