Rational numbers in Python


Tags: python
Reading time: about 1 minute
In []:
 

Some markdown content.

In [2]:
_Rational = namedtuple("_Rational", "num denom")
_Rational = functools.total_ordering(_Rational)

def rational(num, denom=1):
	return _Rational(num, denom).simplify()
In [3]:
def _(self):
	if self.denom == 1:
		return str(self.num)
	return f"{self.num} / {self.denom}"

_Rational.__repr__ = _
In [4]:
def _(self):
	gcd = math.gcd(self.num, self.denom)
	return _Rational(self.num // gcd, self.denom // gcd)

_Rational.simplify = _
In [5]:
rational(4, 2)
rational(4, 2).simplify()
Out [5]:
2
Out [5]:
2

Citation

If you find this work useful, please cite it as:
@article{yaltiraklirationalnumberspython,
  title   = "Rational numbers in Python",
  author  = "Yaltirakli, Gokberk",
  journal = "gkbrk.com",
  year    = "2024",
  url     = "https://www.gkbrk.com/rational-numbers-python"
}
Not using BibTeX? Click here for more citation styles.
IEEE Citation
Gokberk Yaltirakli, "Rational numbers in Python", December, 2024. [Online]. Available: https://www.gkbrk.com/rational-numbers-python. [Accessed Dec. 30, 2024].
APA Style
Yaltirakli, G. (2024, December 30). Rational numbers in Python. https://www.gkbrk.com/rational-numbers-python
Bluebook Style
Gokberk Yaltirakli, Rational numbers in Python, GKBRK.COM (Dec. 30, 2024), https://www.gkbrk.com/rational-numbers-python

Comments

© 2024 Gokberk Yaltirakli