fractions.py

Created by alain-busser

Created on April 25, 2018

632 Bytes

le module fractions permet de faire du calcul sur les fractions. Pour entrer 3/5 faire Fraction(3,5). Les opérations se font comme avec les autres nombres: a+b, a-b, a*b, a/b et a**n.

actuellement seules l’addition et la soustraction fonctionnent, probablement un bug de micropython (?)


def gcd(a,b):
  while b>0: a,b=b,a%b
  return a
class Fraction:
  def __init__(self,n=0,d=1):
    self.n=n//gcd(n,d)
    self.d=d//gcd(n,d)
  def __str__(self):
    return str(self.n)+"/"+str(self.d)
  def __repr__(self):
    return str(self.n)+"/"+str(self.d)
  def __add__(self,o):
    return Fraction(self.n*o.d+self.d*o.n,self.d*o.d)
  def __sub__(self,o):
    return Fraction(self.n*o.d-self.d*o.n,self.d*o.d)
  def __mul__(self,o):
    return Fraction(self.n*o.n,self.d*o.d)
  def __truediv__(self,o):
    return Fraction(self.n*o.d,self.d*o.n)
  def __pow__(self,e):
    return Fraction(self.n**e,self.d**e)

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.