Compare commits

...

2 Commits

Author SHA1 Message Date
1347c30b92 Feat: simplified version for Fraction and MOFraction
All checks were successful
continuous-integration/drone/push Build is passing
2021-09-26 08:58:42 +02:00
bf55470467 Feat: make MOFraction comparable 2021-09-26 08:29:07 +02:00
2 changed files with 62 additions and 1 deletions

View File

@ -269,7 +269,31 @@ class Fraction(Token):
>>> f.decimal >>> f.decimal
<Decimal 0.3333333333333333333333333333> <Decimal 0.3333333333333333333333333333>
""" """
return Decimal(_Decimal(self._mo.numerator._value) / _Decimal(self._mo.denominator._value)) 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

@ -9,6 +9,8 @@
from mapytex.calculus.core.tree import Tree from mapytex.calculus.core.tree import Tree
from .mo import Molecule, MO from .mo import Molecule, MO
from .atoms import MOnumber from .atoms import MOnumber
from decimal import Decimal
from ..arithmetic import gcd
__all__ = ["MOFraction"] __all__ = ["MOFraction"]
@ -70,6 +72,10 @@ class MOFraction(Molecule):
def denominator(self): def denominator(self):
return self._denominator return self._denominator
@property
def _value(self):
return Decimal(self._numerator._value) / Decimal(self._denominator._value)
def inverse(self): def inverse(self):
""" return the inverse fraction """ """ return the inverse fraction """
return MOFraction(self._denominator, self._numerator, self.negative) return MOFraction(self._denominator, self._numerator, self.negative)
@ -90,6 +96,37 @@ class MOFraction(Molecule):
else: else:
raise NotImplementedError 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' # Reglages pour 'vim'