Feat: simplified version for Fraction and MOFraction
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Bertrand Benjamin 2021-09-26 08:58:42 +02:00
parent bf55470467
commit 1347c30b92
2 changed files with 55 additions and 0 deletions

View File

@ -271,6 +271,29 @@ class Fraction(Token):
"""
return Decimal(self._mo._value)
def simplified(self):
""" Get the irreductible version of self
:example:
>>> f = Fraction("3/4")
>>> f.simplified()
<Fraction 3 / 4>
>>> f = Fraction("12/9")
>>> f.simplified()
<Fraction 4 / 3>
>>> f = Fraction("12/4")
>>> f.simplified()
<Integer 3>
"""
simplified = self._mo.simplified()
if isinstance(simplified, MOnumber):
return Integer(simplified)
return Fraction(simplified)
# -----------------------------

View File

@ -10,6 +10,7 @@ from mapytex.calculus.core.tree import Tree
from .mo import Molecule, MO
from .atoms import MOnumber
from decimal import Decimal
from ..arithmetic import gcd
__all__ = ["MOFraction"]
@ -95,6 +96,37 @@ class MOFraction(Molecule):
else:
raise NotImplementedError
def simplified(self):
""" Simplified version of self
:examplex
>>> f = MOFraction(2, 3)
>>> f
<MOFraction 2 / 3>
>>> f.simplified()
<MOFraction 2 / 3>
>>> f = MOFraction(2, 6)
>>> f
<MOFraction 2 / 6>
>>> f.simplified()
<MOFraction 1 / 3>
>>> f = MOFraction(32, 24)
>>> f.simplified()
<MOFraction 4 / 3>
>>> f = MOFraction(32, 8)
>>> f.simplified()
<MOnumber 4>
"""
frac_gcd = gcd(self.numerator._value, self.denominator._value)
new_num = self.numerator._value / frac_gcd
new_denom = self.denominator._value / frac_gcd
if new_denom == 1:
return MOnumber(new_num)
return MOFraction(new_num, new_denom)
# -----------------------------
# Reglages pour 'vim'