예제 #1
0
def creerPolydegre2(nb_racines=2, rac_radical=True, rac_quotient=False):
    if nb_racines == 2:
        redo = True
        while redo:
            a = randrange(1, 4) * (-1) ** randrange(2)
            alpha = randrange(1, 10) * (-1) ** randrange(2)
            beta = randrange(1, 10)
            gamma = [1, randrange(1, 6)][rac_radical]
            if rac_quotient:
                den = randrange(2, 6)
                while pgcd(alpha, den) != 1 or pgcd(beta, den) != 1:
                    den = randrange(2, 6)
                alpha = Fraction(alpha, den)
                beta = Fraction(beta, den)
            b = -2 * alpha * a
            c = a * (alpha ** 2 - gamma * beta ** 2)
            if abs(c) <= 10 and c != 0 and not factoriser(repr(Polynome([[a, 2], [b, 1], [c, 0]]))): redo = False
            if c.denominator != 1:
                c = 'Fraction(%s, %s)' % (c.numerator, c.denominator)
            else:
                c = c.numerator
            if b.denominator != 1:
                b = 'Fraction(%s, %s)' % (b.numerator, b.denominator)
            else:
                b = b.numerator
        return Polynome([[a, 2], [b, 1], [c, 0]])
    elif nb_racines == 1:
        a, b = valeur_alea(-9, 9), valeur_alea(-9, 9)
        return Polynome([[a ** 2, 2], [2 * a * b, 1], [b ** 2, 0]])
    else:
        pol = [[valeur_alea(-9, 9), 2 - dummy] for dummy in range(3)]
        while pol[1][0] ** 2 - 4 * pol[0][0] * pol[2][0] >= 0:
            pol = [[valeur_alea(-9, 9), 2 - dummy] for dummy in range(3)]
        return Polynome(pol)
예제 #2
0
def creerPolydegre2(nb_racines=2, rac_radical=True, rac_quotient=False):
    if nb_racines == 2:
        redo = True
        while redo:
            a = randrange(1, 4) * (-1) ** randrange(2)
            alpha = randrange(1, 10) * (-1) ** randrange(2)
            beta = randrange(1, 10)
            gamma = [1, randrange(1, 6)][rac_radical]
            if rac_quotient:
                den = randrange(2, 6)
                while pgcd(alpha, den) != 1 or pgcd(beta, den) != 1:
                    den = randrange(2, 6)
                alpha = Fraction(alpha, den)
                beta = Fraction(beta, den)
            b = -2 * alpha * a
            c = a * (alpha ** 2 - gamma * beta ** 2)
            if abs(c) <= 10 and c != 0 and not factoriser(repr(Polynome([[a, 2], [b, 1], [c, 0]]))): redo = False
            if c.denominator != 1:
                c = 'Fraction(%s, %s)' % (c.numerator, c.denominator)
            else:
                c = c.numerator
            if b.denominator != 1:
                b = 'Fraction(%s, %s)' % (b.numerator, b.denominator)
            else:
                b = b.numerator
        return Polynome([[a, 2], [b, 1], [c, 0]])
    elif nb_racines == 1:
        a, b = valeur_alea(-9, 9), valeur_alea(-9, 9)
        return Polynome([[a ** 2, 2], [2 * a * b, 1], [b ** 2, 0]])
    else:
        pol = [[valeur_alea(-9, 9), 2 - dummy] for dummy in range(3)]
        while pol[1][0] ** 2 - 4 * pol[0][0] * pol[2][0] >= 0:
            pol = [[valeur_alea(-9, 9), 2 - dummy] for dummy in range(3)]
        return Polynome(pol)
예제 #3
0
def valeurs_puissances():  # renvoie un tuple contenant les valeurs pour les deux exercices sur les puissances
    from math import floor, log10
    (maxi, emax) = (10, 2)
    while True:
        (b1, b2) = (valeur_alea(2, maxi), valeur_alea(2, maxi))
        (b1, b2) = (b1 / pgcd(b1, b2), b2 / pgcd(b1, b2))
        if b1 != 1 and b2 != 1:
            break
    while True:
        (n1, n2) = ((b1 * valeur_alea(2, maxi)) * 10 ** randrange(-emax,
                    emax), (b2 * valeur_alea(2, maxi)) * 10 ** randrange(-emax,
                    emax))
        n3 = ((b1 * b2) * choice((2, 4, 5, 8))) * 10 ** randrange(-emax,
                emax)
        if int(floor(log10(((n1 * n2) * 1.) / n3))) != 0 and n1 != 1 and \
            n2 != 1 and n3 != 1:
            break
    (e1, e2, e3, e4) = (valeur_alea(-10, 10), valeur_alea(-10, 10),
                        valeur_alea(2, 10), valeur_alea(2, 5))
    a = verifie_type((n1, n2, n3, e1, e2, e3, e4))
    while True:
        (b1, b2) = (valeur_alea(2, maxi), valeur_alea(2, maxi))
        (b1, b2) = (b1 / pgcd(b1, b2), b2 / pgcd(b1, b2))
        if b1 != 1 and b2 != 1:
            break
    (n1, n2) = ((b1 * valeur_alea(2, maxi)) * 10 ** randrange(-emax, emax + 
                1), (b2 * valeur_alea(2, maxi)) * 10 ** randrange(-emax,
                emax + 1))
    n3 = ((b1 * b2) * choice((1, 2, 4, 5, 8))) * 10 ** randrange(-emax,
            emax + 1)
    (e1, e2, e3, e4) = (valeur_alea(-10, 10), valeur_alea(-10, 10),
                        valeur_alea(-10, -2), valeur_alea(2, 5))
    b = verifie_type((n1, n2, n3, e1, e2, e3, e4))
    return (a, b)
예제 #4
0
def valeurs_prod_parenth():  # cree 3 fractions et un tuple de signes (*,+)
    while True:
        (base1, base2) = (valeur_alea(2, 13), valeur_alea(2, 13))
        lepgcd = pgcd(base1, base2)
        (base1, base2) = (base1 // lepgcd, base2 // lepgcd)
        if base1 != 1 and base2 != 1:
            break
    while True:
        n2 = valeur_alea(-13, 13)
        lepgcd = pgcd(n2, base1)
        if lepgcd == 1:
            break
    while True:
        n3 = valeur_alea(-13, 13)
        lepgcd = pgcd(n3, base2)
        if lepgcd == 1:
            break
    while True:
        (n1, d1) = (valeur_alea(-10, 10), valeur_alea(2, 10))
        lepgcd = pgcd(n1, d1)
        if lepgcd != n1 and lepgcd != d1:
            break
    (n1, d1) = (n1 // lepgcd, d1 // lepgcd)
    if randrange(2) == 0:
        s1 = '*'
    else:
        s1 = ':'
    if randrange(2) == 0:
        s2 = '+'
    else:
        s2 = '-'
    return ((n1, d1), (n2, base1), (n3, base2), (s1, s2))
예제 #5
0
def valeurs_somme_prod():  # cree 3 fractions et un tuple de signes (+,*)
    while True:
        (base1, base2) = (valeur_alea(-13, 13), valeur_alea(-13, 13))
        lepgcd = pgcd(base1, base2)
        (base1, base2) = (base1 // lepgcd, base2 // lepgcd)
        if base1 != 1 and base2 != 1:
            break
    (n2, d2) = (base1 * valeur_alea(-10, 10), abs(base2 * valeur_alea(2,
                10)))
    lepgcd = pgcd(n2, d2)
    (n2, d2) = (n2 // lepgcd, d2 // lepgcd)
    (n3, d3) = (base2 * valeur_alea(-10, 10), abs(base1 * valeur_alea(2,
                10)))
    lepgcd = pgcd(n3, d3)
    (n3, d3) = (n3 // lepgcd, d3 // lepgcd)
    (n1, d1) = (base1 * valeur_alea(-10, 10), abs(pgcd(d2, base2 * 
                valeur_alea(2, 10))))
    lepgcd = pgcd(n1, d1)
    (n1, d1) = (n1 // lepgcd, d1 // lepgcd)
    if randrange(2) == 0:
        s1 = '+'
    else:
        s1 = '-'
    if randrange(2) == 0:
        s2 = '*'
    else:
        s2 = ':'
    if s2 == '*':
        return ((n1, d1), (n2, d2), (n3, d3), (s1, s2))
    else:
        return ((n1, d1), (n2, d2), (d3, n3), (s1, s2))
예제 #6
0
 def calcul(self, argument):
     if isinstance(argument, Entier):
         if float(argument) < 0:
             arg = ur"\left( {} \right)".format(argument.latex())
         else:
             arg = argument.latex()
         yield self.expression(ur"\times " + arg)
         if isinstance(self.coeff.simplifie(), Fraction):
             yield Fraction(
                         self.coeff.numerateur * argument.valeur,
                         self.coeff.denominateur,
                         ).latex()
             if pgcd(self.coeff.numerateur * argument.valeur, self.coeff.denominateur) != 1:
                 yield self.resultat(argument).latex()
         else:
             yield self.resultat(argument).latex()
     else:
         yield self.expression(ur"\times " + argument.latex())
         yield Fraction(
             self.coeff.numerateur * argument.numerateur,
             self.coeff.denominateur * argument.denominateur,
             ).latex()
         if pgcd(
             self.coeff.numerateur * argument.numerateur,
             self.coeff.denominateur * argument.denominateur,
             ) != 1:
             yield self.resultat(argument).latex()
예제 #7
0
def id_rem():
    """Génère un exercice de développement des 3 identités remarquables avec une situation piège.
    Dans un premier temps, on n'utilise que des nombres entiers, puis des fractions, puis l'opposé 
    d'une expression littérale.
    """

    l = [randrange(1, 11) for dummy in range(14)]
    while pgcd(l[8], l[9]) != 1 or pgcd(l[10], l[11]) != 1 or (l[9] == 1 and l[11] == 1):
        # On crée deux rationnels irréductibles non tous deux entiers.
        l = [randrange(1, 11) for dummy in range(14)]
    lpoly = [id_rem1(l[0], l[1]), id_rem2(l[2], l[3]), id_rem3(l[4], l[5]), id_rem4(l[6], l[7])]
    shuffle(lpoly)
    lid = [id_rem1, id_rem2, id_rem3, id_rem4]
    lpoly2 = [lid.pop(randrange(4))(Fraction(l[8], l[9]), Fraction(l[10], l[11]))]
    lpoly2.append('-' + lid.pop(randrange(3))(l[12], l[13]))
    shuffle(lpoly2)
    lpoly.extend(lpoly2)
    expr = [Priorites3.texify([Priorites3.splitting(lpoly[i])]) for i in range(6)]
    exo = ["\\exercice", u"Développer chacune des expressions littérales suivantes :"]
    exo.append("\\begin{multicols}{2}")
    exo.append('\\\\\n'.join(['$%s=%s$' % (chr(i + 65), expr[i][0]) for i in range(6)]))
    exo.append("\\end{multicols}")
    cor = ["\\exercice*", u"Développer chacune des expressions littérales suivantes :"]
    cor.append("\\begin{multicols}{2}")
    for i in range(6):
        dev = Priorites3.texify(Priorites3.priorites(lpoly[i]))
        dev.insert(0, expr[i][0])
        cor.append('\\\\\n'.join(['$%s=%s$' % (chr(i + 65), dev[j]) for j in range(len(dev) - 1)]))
        cor.append('\\\\')
        cor.append('\\fbox{$%s=%s$}\\\\\n' % (chr(i + 65), dev[-1]))
    cor.append("\\end{multicols}")

    return exo, cor
예제 #8
0
파일: Racine.py 프로젝트: Azixx/pyromaths
    def simplifie(self, detail=False):
        liste_detail = []
        coeff, radicande = simplifie_racine(self.radicande)
        numerateur = self.numerateur
        if self.radicande != 0:
            if self.coeff == 1:
                det_coeff = "+ "
            elif self.coeff == -1:
                det_coeff = "- "
            else:
                det_coeff = "%s\\times " % (self.coeff)
            if coeff != 1 or radicande == 1:
                det_coeff += str(coeff)
        else:
            det_coeff = "0"
        if radicande == 1:
            # det_coeff="%s\\times%s"%(tTeX(self.coeff),coeff)
            liste_detail.append("\\dfrac{%s %s}{%s}" % \
                                    (self.numerateur, det_coeff , self.denominateur))
            radicande = 0
            numerateur = self.numerateur + (self.coeff) * int(coeff)
            coeff = 0

        if coeff != 1:
            liste_detail.append(
                str(
                    RacineDegre2(numerateur, self.denominateur, det_coeff,
                                 radicande)))

        coeff = (self.coeff) * int(coeff)

        simplifie = pgcd(pgcd(coeff, numerateur), self.denominateur)
        numerateur = numerateur // simplifie
        coeff = coeff // simplifie
        denominateur = self.denominateur // simplifie
        if simplifie != 1:
            if radicande != 0 or denominateur != 1:
                det_numerateur = "%s_{\\times %s}" % (numerateur,
                                                      pTeX(simplifie))
                det_denominateur = "%s_{\\times %s}" % (denominateur,
                                                        pTeX(simplifie))
                det_coeff = "%s_{\\times %s}" % (coeff, pTeX(simplifie))
                liste_detail.append(
                    str(
                        RacineDegre2(det_numerateur, det_denominateur,
                                     det_coeff, radicande)))
            liste_detail.append(
                str(RacineDegre2(numerateur, denominateur, coeff, radicande)))
        if detail:
            return RacineDegre2(numerateur, denominateur, coeff,
                                radicande), liste_detail
        return RacineDegre2(numerateur, denominateur, coeff, radicande)
예제 #9
0
def decomp_prod(a, b):  # renvoie un tuple contenant les deux fractions apres simplification et un tuple contenant les nb par lesquels on

    # simplifie le produit de fractions

    c = pgcd(a[0], b[1])
    d = pgcd(a[1], b[0])
    sgn1 = signe(a[1])
    sgn2 = signe(b[1])
    if c == d == 1:
        return (((sgn1 * a[0]) // c, (sgn1 * a[1]) // d), ((sgn2 * b[0]) // 
                d, (sgn2 * b[1]) // c), '')
    else:
        return (((sgn1 * a[0]) // c, (sgn1 * a[1]) // d), ((sgn2 * b[0]) // 
                d, (sgn2 * b[1]) // c), (c, d))
예제 #10
0
def valeurs_reciproque_thales():
    while True:
        (a, b, c, d) = (random.randrange(2, 50), random.randrange(2, 50),
                        random.randrange(2, 20), random.randrange(2, 20))
        p1 = pgcd(a, b)
        (a, b) = (a / p1, b / p1)
        if c < d:
            (c, d) = (d, c)
        if a != b and int(c / d) != (c * 1.0) / d and 10 < a * c < 200 and \
            10 < a * d < 200 and 10 < b * c < 200 and 10 < b * d < 200 and \
            .3 < (d * 1.0) / c < .7:
            break
    t = valeur_alea(-1, 1)  # -1 si papillon, 1 si triangle
    r = random.randrange(5)
    while r == 2:
        r = random.randrange(5)
    angle = random.randrange(15, 105)
    valeurs = (
        (a * c) / 10.0,
        (b * c) / 10.0,
        0,
        (a * d) / 10.0,
        (b * d) / 10.0,
        0,
        (a * c - (t * a) * d) / 10.0,
        (b * c - (t * b) * d) / 10.0,
        angle,
        t,
        r,
        )
    return valeurs
예제 #11
0
    def decompose(self):
        """**decompose**\ (*object*)

        Retourne une décomposition de la fraction afin de la simplifier

            >>> from pyromaths.classes.Fractions import Fraction
            >>> Fraction.decompose(Fraction(8,20))
            Fraction("2*4", "5*4", "s")

        :param type: Fraction
        :rtype: Fraction
        """
        if isinstance(self.n, str): self.n = eval(self.n)
        if isinstance(self.d, str): self.d = eval(self.d)
        conv = False
        if isinstance(self.n, SquareRoot):
            s = self.n.simplifie()
            if s != self.n:
                self.n = s
                conv = True
        if isinstance(self.d, SquareRoot):
            s = self.d.simplifie()
            if s != self.d:
                self.d = s
                conv = True
        if conv:
            return self
        if self.d == self.n:
            return 1
        else:
            lepgcd = pgcd(self.n, self.d)
            if lepgcd == 1:
                return self
            else:
                return Fraction("%r*%s" % (self.n // lepgcd, lepgcd), "%r*%s" % (self.d // lepgcd, lepgcd), "s")
예제 #12
0
    def __init__(self):
        val = [valeur_alea(-9, 9), valeur_alea(-9, 9)]
        val.append(Fraction(valeur_alea(-9, 9), val[0]))
        while val[2].d == 1:
            val = [valeur_alea(-9, 9), valeur_alea(-9, 9)]
            val.append(Fraction(valeur_alea(-9, 9), val[0]))

        pol = [[val[0], 2], [(-val[0] * (val[1] * val[2].d + val[2].n)) / val[2].d, 1], [(val[0] * val[1] * val[2].n) / val[2].d, 0]]
        shuffle(pol)
        exercice = [[list(pol), val[1], val[2]]]

        pol = [creerPolydegre2(nb_racines=0).monomes]
        pol.append(creerPolydegre2(nb_racines=1).monomes)
        a, b = valeur_alea(-9, 9), valeur_alea(-9, 9)
        sgn = [1, -1][randrange(2)]
        pol.append([[sgn * a ** 2, 2], [-sgn * b ** 2, 0]])
        a, b = valeur_alea(-9, 9), valeur_alea(-9, 9)
        pol.append([[a, 2], [b, 1]])
        a, b = valeur_alea(-9, 9), valeur_alea(-9, 9)
        while abs(pgcd(a, b)) != 1:
            a, b = valeur_alea(-9, 9), valeur_alea(-9, 9)
        pol.append([[a, 2], [b, 0]])
        pol.pop(randrange(1, len(pol)))
        pol.pop(randrange(1, len(pol)))
        pol.pop(randrange(1, len(pol)))
        shuffle(pol)
        exercice.append(pol)

        self.exercice = exercice
예제 #13
0
def resolution_rec_thales1(n, v):
    (d, t) = ([], '')
    for i in range(2):
        d.extend([creer_noms(n, i), creer_noms(n, i + 3), nombre(v[i]),
                 nombre(v[i + 3])])
        if valeur_exacte(v[i] / v[i + 3], approx=5).count('='):
            d.append(valeur_exacte(v[i] / v[i + 3], approx=5, unit=0))
        else:
            if v[i] != int(v[i]) or v[i + 3] != int(v[i + 3]):
                p = pgcd(int(v[i] * 10), int(v[i + 3] * 10))
                if p == 1:
                    t = '=\\cfrac{%s}{%s}' % (nombre(v[i] * 10), nombre(v[i +
                            3] * 10))
                else:
                    t = '=\\cfrac{%s_{\\div%s}}{%s_{\\div%s}}' % (nombre(v[i] *
                            10), p, nombre(v[i + 3] * 10), p)
            if fractions.simplifie((int(v[i] * 10), int(v[i + 3] * 10))):
                d.append(t + '=' + fractions.tex_frac(fractions.simplifie((int(v[i] *
                         10), int(v[i + 3] * 10)))))
            else:
                d.append(t + '=' + fractions.tex_frac((int(v[i] * 10),
                         int(v[i + 3] * 10))))
    d.extend([creer_noms(n, 0), creer_noms(n, 3), creer_noms(n, 1),
             creer_noms(n, 4), creer_noms(n, 2), creer_noms(n, 5)])
    return tuple(d)
예제 #14
0
def resolution_rec_thales1(n, v):
    (d, t) = ([], '')
    for i in range(2):
        d.extend([creer_noms(n, i), creer_noms(n, i + 3), nombre(v[i]),
                 nombre(v[i + 3])])
        if valeur_exacte(v[i] / v[i + 3], approx=5).count('='):
            d.append(valeur_exacte(v[i] / v[i + 3], approx=5, unit=0))
        else:
            if v[i] != int(v[i]) or v[i + 3] != int(v[i + 3]):
                p = pgcd(int(v[i] * 10), int(v[i + 3] * 10))
                if p == 1:
                    t = '=\\cfrac{%s}{%s}' % (nombre(v[i] * 10), nombre(v[i +
                            3] * 10))
                else:
                    t = '=\\cfrac{%s_{\\div%s}}{%s_{\\div%s}}' % (nombre(v[i] *
                            10), p, nombre(v[i + 3] * 10), p)
            if fractions.simplifie((int(v[i] * 10), int(v[i + 3] * 10))):
                d.append(t + '=' + fractions.tex_frac(fractions.simplifie((int(v[i] *
                         10), int(v[i + 3] * 10)))))
            else:
                d.append(t + '=' + fractions.tex_frac((int(v[i] * 10),
                         int(v[i + 3] * 10))))
    d.extend([creer_noms(n, 0), creer_noms(n, 3), creer_noms(n, 1),
             creer_noms(n, 4), creer_noms(n, 2), creer_noms(n, 5)])
    return tuple(d)
예제 #15
0
def valeurs_reciproque_thales():
    while True:
        (a, b, c, d) = (random.randrange(2, 50), random.randrange(2, 50),
                        random.randrange(2, 20), random.randrange(2, 20))
        p1 = pgcd(a, b)
        (a, b) = (a / p1, b / p1)
        if c < d:
            (c, d) = (d, c)
        if a != b and int(c / d) != (c * 1.0) / d and 10 < a * c < 200 and \
            10 < a * d < 200 and 10 < b * c < 200 and 10 < b * d < 200 and \
            .3 < (d * 1.0) / c < .7:
            break
    t = valeur_alea(-1, 1)  # -1 si papillon, 1 si triangle
    r = random.randrange(5)
    while r == 2:
        r = random.randrange(5)
    angle = random.randrange(15, 105)
    valeurs = (
        (a * c) / 10.0,
        (b * c) / 10.0,
        0,
        (a * d) / 10.0,
        (b * d) / 10.0,
        0,
        (a * c - (t * a) * d) / 10.0,
        (b * c - (t * b) * d) / 10.0,
        angle,
        t,
        r,
        )
    return valeurs
예제 #16
0
    def __init__(self):
        val = [valeur_alea(-9, 9), valeur_alea(-9, 9)]
        val.append(Fraction(valeur_alea(-9, 9), val[0]))
        while val[2].d == 1:
            val = [valeur_alea(-9, 9), valeur_alea(-9, 9)]
            val.append(Fraction(valeur_alea(-9, 9), val[0]))

        pol = [[val[0], 2], [(-val[0] * (val[1] * val[2].d + val[2].n)) / val[2].d, 1], [(val[0] * val[1] * val[2].n) / val[2].d, 0]]
        shuffle(pol)
        exercice = [[list(pol), val[1], val[2]]]

        pol = [creerPolydegre2(nb_racines=0).monomes]
        pol.append(creerPolydegre2(nb_racines=1).monomes)
        a, b = valeur_alea(-9, 9), valeur_alea(-9, 9)
        sgn = [1, -1][randrange(2)]
        pol.append([[sgn * a ** 2, 2], [-sgn * b ** 2, 0]])
        a, b = valeur_alea(-9, 9), valeur_alea(-9, 9)
        pol.append([[a, 2], [b, 1]])
        a, b = valeur_alea(-9, 9), valeur_alea(-9, 9)
        while abs(pgcd(a, b)) != 1:
            a, b = valeur_alea(-9, 9), valeur_alea(-9, 9)
        pol.append([[a, 2], [b, 0]])
        pol.pop(randrange(1, len(pol)))
        pol.pop(randrange(1, len(pol)))
        pol.pop(randrange(1, len(pol)))
        shuffle(pol)
        exercice.append(pol)

        self.exercice = exercice
예제 #17
0
    def __str__(self):
        r"""**str**\ (*object*)

        Renvoie une version LaTeX de la :class:`Fraction`.
            >>> from pyromaths.classes.Fractions import Fraction
            >>> str(Fraction(8,1))
            '8'
            >>> str(Fraction(5,6))
            '\\dfrac{5}{6}'
            >>> str(Fraction('-5*2', '3*2', 'r'))
            '\\dfrac{-5_{\\times 2}}{3_{\\times 2}}'
            >>> str(Fraction('5*-7*2', '11*2*5', 's'))
            '\\dfrac{\\cancel{5}\\times \\left( -7\\right) \\times \\cancel{2}}{11\\times \\cancel{2}\\times \\cancel{5}}'
            >>> str(Fraction('-144', '22', 's'))
            '\\dfrac{-72\\times \\cancel{2}}{11\\times \\cancel{2}}'
            >>> from pyromaths.classes.SquareRoot import SquareRoot
            >>> str(Fraction(SquareRoot([[-10, None], [-1, 80]]), -2))
            '\\dfrac{-10-\\sqrt{80}}{-2}'
            >>> str(Fraction(SquareRoot([[-10, None], [-4, 5]]), -2, 's'))
            '\\dfrac{\\left( 5+2\\,\\sqrt{5}\\right) \\times \\cancel{-2}}{1\\times \\cancel{-2}}'
            
        :rtype: string
        """
        from pyromaths.outils.Priorites3 import splitting
        #=======================================================================
        # print (repr(self))
        #=======================================================================
        if self.n == 0 or self.n == '0':
            return '0'
        lnum, lden = [], []
        if isinstance(self.n, str): lnum = splitting(self.n)
        if isinstance(self.d, str): lden = splitting(self.d)
        if len(lnum) == 1: self.n, lnum = eval(self.n), []
        if len(lden) == 1: self.d, lden = eval(self.d), []
        if self.d == 1:
            return (str(self.n), texify([lnum])[0])[lnum != []]
        if self.code == "r":
            # lnum et lden doivent être définis et se terminer par [..., '*', valeur]
            if not lnum or not lden or lnum[-2:] != lden[-2:]:
                raise ValueError(u'Mauvais usage de l\'étiquettes "r" dans %r' % self)
            lden[-2], lden[-1], lnum[-2], lnum[-1] = [lden[-2], 'indice'], [lden[-1], 'indice'], [lnum[-2], 'indice'], [lnum[-1], 'indice']
            return '\\dfrac{%s}{%s}' % (texify([lnum])[0], texify([lden])[0])
        if self.code == "s":
            if isinstance(self.n, (int, float, SquareRoot)) and isinstance(self.d, (int, float, SquareRoot)):
                lepgcd = pgcd(self.n, self.d)
                lnum, lden = [repr(self.n // lepgcd), '*', [str(lepgcd), 'cancel']], [repr(self.d // lepgcd), '*', [str(lepgcd), 'cancel']]
            else:
                for i in range(len(lnum)):
                    if lnum[i] != '*' and lden.count(lnum[i]):
                        # On doit simplifier la fraction par ce nombre
                        j = lden.index(lnum[i])
                        lden[j] = [lden[j], 'cancel']
                        lnum[i] = [lnum[i], 'cancel']
            return '\\dfrac{%s}{%s}' % (texify([lnum])[0], texify([lden])[0])
        s = r'\dfrac'
        s += '{%s}' % (self.n, texify([lnum])[0])[lnum != []]
        s += '{%s}' % (self.d, texify([lden])[0])[lden != []]
        return s
예제 #18
0
파일: Racine.py 프로젝트: Lafrite/pyromaths
    def simplifie(self, detail=False):
        liste_detail = []
        coeff, radicande = simplifie_racine(self.radicande)
        numerateur = self.numerateur
        if self.radicande != 0:
            if self.coeff == 1:
                    det_coeff = "+ "
            elif self.coeff == -1:
                det_coeff = "- "
            else:
                det_coeff = "%s\\times " % (self.coeff)
            if coeff != 1 or radicande == 1:
                det_coeff += str(coeff)
        else:
            det_coeff = "0"
        if radicande == 1:
            # det_coeff="%s\\times%s"%(tTeX(self.coeff),coeff)
            liste_detail.append("\\dfrac{%s %s}{%s}" % \
                                    (self.numerateur, det_coeff , self.denominateur))
            radicande = 0
            numerateur = self.numerateur + (self.coeff) * int(coeff)
            coeff = 0

        if coeff != 1:
            liste_detail.append(str(RacineDegre2(numerateur,
                                                 self.denominateur,
                                                 det_coeff,
                                                 radicande)))

        coeff = (self.coeff) * int(coeff)

        simplifie = pgcd(pgcd(coeff, numerateur), self.denominateur)
        numerateur = numerateur // simplifie
        coeff = coeff // simplifie
        denominateur = self.denominateur // simplifie
        if simplifie != 1:
            if radicande != 0 or denominateur != 1:
                det_numerateur = "%s_{\\times %s}" % (numerateur, pTeX(simplifie))
                det_denominateur = "%s_{\\times %s}" % (denominateur, pTeX(simplifie))
                det_coeff = "%s_{\\times %s}" % (coeff, pTeX(simplifie))
                liste_detail.append(str(RacineDegre2(det_numerateur, det_denominateur, det_coeff, radicande)))
            liste_detail.append(str(RacineDegre2(numerateur, denominateur, coeff, radicande)))
        if detail:
            return RacineDegre2(numerateur, denominateur, coeff, radicande), liste_detail
        return RacineDegre2(numerateur, denominateur, coeff, radicande)
예제 #19
0
 def simplifie(self):
     if self.numerateur % self.denominateur == 0:
         return Entier(self.signe * self.numerateur / self.denominateur)
     diviseur = pgcd(self.numerateur, self.denominateur)
     return Fraction(
             self.numerateur/diviseur,
             self.denominateur/diviseur,
             self.signe,
             )
예제 #20
0
def valeurs_quotient_frac():  # cree 4 fractions et un tuple de signes (+,+)
    while True:
        (n1, d1) = (valeur_alea(-10, 10), valeur_alea(2, 10))
        lepgcd = pgcd(n1, d1)
        if lepgcd != n1 and lepgcd != d1:
            break
    (n1, d1) = (n1 // lepgcd, d1 // lepgcd)
    while True:
        (n3, d3) = (valeur_alea(-10, 10), valeur_alea(2, 10))
        lepgcd = pgcd(n3, d3)
        if lepgcd != n3 and lepgcd != d3:
            break
    (n3, d3) = (n3 // lepgcd, d3 // lepgcd)
    (n2, n4) = (valeur_alea(1, 10), valeur_alea(1, 10))
    if randrange(2) == 0:
        s1 = '+'
    else:
        s1 = '-'
    if randrange(2) == 0:
        s2 = '+'
    else:
        s2 = '-'
    return ((n1, d1), (n2, 1), (n3, d3), (n4, 1), (s1, s2))
예제 #21
0
def InitPoints(minimum=-6.1, maximum=6.1, nbval=3):
    dY = []
    directions = [(-1) ** i for i in range(nbval - 1)]
    directions.append(0)
    shuffle(directions)
    for i in range((nbval - 1) // 2):
        while True:
            a, b = randrange(1, 5), randrange(1, 5)
            if pgcd(a, b) == 1 and a % b != 0:
                dY.append(Fraction(a, b))
                break
    for i in range(nbval - 1 - len(dY)):
        dY.append(randrange(1, 5))
    shuffle(dY)
    for i in range(nbval):
        if directions[i] == 0:
            dY.insert(i, 0)
        else:
            dY[i] = dY[i] * directions[i]
    dY.insert(0, 0)
    dY.append(0)
    redo = True
    while redo:
        lX = [int(minimum) + 1 + int(1.*i * (maximum - minimum - 2) / nbval) + randrange(4) for i in range(nbval)]
        for i in range(len(lX) - 1):
            if lX[i + 1:].count(lX[i]):
                redo = True
                break
            else:
                redo = False
    lX.insert(0, minimum)
    lX.append(maximum)
    lX.sort()
    lY = [randrange(-4, 5)]
    for i in range(1, len(lX)):
        inf = lY[-1] - 4 * int(lX[i] - lX[i - 1])
        sup = lY[-1] + 4 * int(lX[i] - lX[i - 1])
        nY = randrange(int(max(-4, inf)), int(min(5, sup)))
        lY.append(nY)
        #=======================================================================
        # while True:
        #     lg = randrange(1, 4) * (-1) ** randrange(2) * int(lX[i] - lX[i - 1])
        #     nY = lY[-1] + lg
        #     if -4 <= nY <= 4 :
        #         lY.append(nY)
        #         break
        #=======================================================================
    return lX, lY, dY
예제 #22
0
 def resultat(self, argument):
     if isinstance(argument, Entier) and isinstance(self.raison, Entier):
         return Entier(argument.valeur * self.raison.valeur)
     else:
         if isinstance(argument, Entier):
             argument = Fraction(argument.valeur, 1)
         if isinstance(self.raison, Entier):
             raison = Fraction(self.raison.valeur, 1)
         else:
             raison = self.raison
         numerateur = argument.numerateur * raison.numerateur
         denominateur = raison.denominateur * argument.denominateur
         if numerateur % denominateur == 0:
             return Entier(numerateur / denominateur)
         diviseur = pgcd(numerateur, denominateur)
         return Fraction(numerateur/diviseur, denominateur/diviseur)
예제 #23
0
 def calcul(self, argument):
     if argument.valeur < 0:
         arg2 = ur"\left( {} \right)".format(argument.latex())
     else:
         arg2 = argument.latex()
     yield ur"\frac{{ {numerateur}^{{ {argument} }}}}{{ {denominateur}\times{arg2} }}".format(
             numerateur=self.numerateur.latex(),
             denominateur=self.denominateur.latex(),
             argument=argument.latex(),
             arg2=arg2,
         )
     yield ur"\frac{{ {} }}{{ {} }}".format(
             self.numerateur.valeur ** argument.valeur,
             self.denominateur.valeur * argument.valeur,
             )
     if pgcd(
             self.numerateur.valeur ** argument.valeur,
             self.denominateur.valeur * argument.valeur,
             ) != 1:
         yield self.resultat(argument).latex()
예제 #24
0
    def __init__(self):
        [a, b, c, d] = [randrange(-5, 6) for dummy in range(4)]
        while a == 0 or c == 0 or a ** 2 * d - a * b * c + c ** 2 < 0 or carrerise(a ** 2 * d - a * b * c + c ** 2) != 1:
            [a, b, c, d] = [randrange(-5, 6) for dummy in range(4)]
        p1 = str(Polynome([[a, 1], [b, 0]], "m"))
        p2 = str(Polynome([[c, 1], [d, 0]], "m"))
        pol = [Polynome([[1, 2], [p1, 1], [p2, 0]]), randrange(3)]
        exercice = [list(pol)]

        v = [randrange(-4, 5) for dummy in range(6)]
        while v[0] == 0 or v[2] == v[4] == 0 or reduce(lambda x, y: x * y, v) != 0 or v[2] == v[3] == 0 or v[4] == v[5] == 0:
            v = [randrange(-4, 5) for dummy in range(6)]
        lp = [str(Polynome([[v[2 * i] / pgcd(v[2 * i], v[2 * i + 1]), 1], [v[2 * i + 1] / pgcd(v[2 * i], v[2 * i + 1]), 0]], "a")) for i in range(3)]
        pol = Polynome([[lp[0], 2], [lp[1], 1], [lp[2], 0]])
        vi = Fraction(-v[1], v[0])
        racine = randrange(-4, 5)
        while racine == vi or racine == 0:
            racine = randrange(-4, 5)
        if vi.d == 1 : vi = str(vi.n)
        else: vi = str(vi)
        exercice.append([list(pol), vi, racine])
        self.exercice = exercice
예제 #25
0
    def simplifie(self):
        """**simplifie**\ (*object*)

        Retourne une version irréductible de la fraction

            >>> from pyromaths.classes.Fractions import Fraction
            >>> repr(Fraction.simplifie(Fraction(2*4,5*4)))
            Fraction(2, 5)
            >>> repr(Fraction.simplifie(Fraction('2*4','5*4')))
            Fraction(2, 5)

        :param type: Fraction
        :rtype: Fraction
        """
        conv = False
        if isinstance(self.n, str):
            self.n = eval(self.n)
            conv = True
        if isinstance(self.d, str):
            self.d = eval(self.d)
            conv = True
        if conv: self = Fraction(self.n, self.d)
        conv = False
        if isinstance(self.n, SquareRoot):
            s = self.n.simplifie()
            if s != self.n:
                self.n = s
                conv = True
        if isinstance(self.d, SquareRoot):
            s = self.d.simplifie()
            if s != self.d:
                self.d = s
                conv = True
        if conv: return self
        s = pgcd(self.n, self.d)
        if self.d != s:
            return Fraction(self.n // s, self.d // s)
        else:
            return self.n // s
예제 #26
0
    def __init__(self):
        [a, b, c, d] = [randrange(-5, 6) for dummy in range(4)]
        while a == 0 or c == 0 or a ** 2 * d - a * b * c + c ** 2 < 0 or carrerise(a ** 2 * d - a * b * c + c ** 2) != 1:
            [a, b, c, d] = [randrange(-5, 6) for dummy in range(4)]
        p1 = str(Polynome([[a, 1], [b, 0]], "m"))
        p2 = str(Polynome([[c, 1], [d, 0]], "m"))
        pol = [Polynome([[1, 2], [p1, 1], [p2, 0]]), randrange(3)]
        exercice = [list(pol)]

        v = [randrange(-4, 5) for dummy in range(6)]
        while v[0] == 0 or v[2] == v[4] == 0 or reduce(lambda x, y: x * y, v) != 0 or v[2] == v[3] == 0 or v[4] == v[5] == 0:
            v = [randrange(-4, 5) for dummy in range(6)]
        lp = [str(Polynome([[v[2 * i] / pgcd(v[2 * i], v[2 * i + 1]), 1], [v[2 * i + 1] / pgcd(v[2 * i], v[2 * i + 1]), 0]], "a")) for i in range(3)]
        pol = Polynome([[lp[0], 2], [lp[1], 1], [lp[2], 0]])
        vi = Fraction(-v[1], v[0])
        racine = randrange(-4, 5)
        while racine == vi or racine == 0:
            racine = randrange(-4, 5)
        if vi.d == 1 : vi = str(vi.n)
        else: vi = str(vi)
        exercice.append([list(pol), vi, racine])
        self.exercice = exercice
예제 #27
0
    def simplifie(self):
        """**simplifie**\ (*object*)

        Retourne une version irréductible de la fraction

            >>> from pyromaths.classes.Fractions import Fraction
            >>> Fraction.simplifie(Fraction(2*4,5*4))
            Fraction(2, 5)
            >>> Fraction.simplifie(Fraction('2*4','5*4'))
            Fraction(2, 5)

        :param type: Fraction
        :rtype: Fraction
        """
        conv = False
        if isinstance(self.n, str):
            self.n = eval(self.n)
            conv = True
        if isinstance(self.d, str):
            self.d = eval(self.d)
            conv = True
        if conv : self = Fraction(self.n, self.d)
        conv = False
        if isinstance(self.n, SquareRoot):
            s = self.n.simplifie()
            if s != self.n:
                self.n = s
                conv = True
        if isinstance(self.d, SquareRoot):
            s = self.d.simplifie()
            if s != self.d:
                self.d = s
                conv = True
        if conv: return self
        s = pgcd(self.n, self.d)
        if self.d != s:
            return Fraction(self.n // s, self.d // s)
        else:
            return self.n // s
예제 #28
0
    def calcul(self, argument):
        yield ur"{} \times {}".format(self.raison.latex(), argument.latex())
        resultat = self.resultat(argument).latex()
        if isinstance(resultat, Entier):
            yield self.resultat(argument).latex()
        else:
            if isinstance(argument, Entier):
                argument = Fraction(argument.valeur, 1)
            raison = self.raison
            if isinstance(raison, Entier):
                raison = Fraction(raison.valeur, 1)
            numerateur = argument.numerateur * raison.numerateur
            denominateur = raison.denominateur * argument.denominateur
            yield ur"\frac{{ {} }}{{ {} }}".format(numerateur, denominateur)
            if numerateur % denominateur == 0:
                yield Entier(numerateur / denominateur).latex()
                return

            diviseur = pgcd(numerateur, denominateur)
            if diviseur == 1:
                return

            yield Fraction(numerateur/diviseur, denominateur/diviseur).latex()
예제 #29
0
    def traitement(self, final=False):
        """**traitement**\ (*object*,\ *self*)

        Finit la mise au même dénominateur ou la simplification de la fraction.
        Si *final* est vrai, alors essaie de simplifier la fraction.

            >>> from pyromaths.classes.Fractions import Fraction
            >>> repr(Fraction("3*4", "3*7", "r").traitement())
            Fraction(12, 21)
            >>> repr(Fraction("3*4", "3*7", "s").traitement())
            Fraction(4, 7)
            >>> repr(Fraction(12, 21).traitement())
            Fraction(12, 21)
            >>> repr(Fraction(12, 21).traitement(True))
            Fraction("4*3", "7*3", "s")

        :param: final
        :type: boolean
        :rtype: Fraction
        """
        if self.code == "r":
            if isinstance(self.n, str): n = eval(self.n)
            else: n = self.n
            if isinstance(self.d, str): d = eval(self.d)
            else: d = self.d
            return Fraction(n, d)
        if self.code == "s":
            if isinstance(self.n, str): n = eval(self.n)
            else: n = self.n
            if isinstance(self.d, str): d = eval(self.d)
            else: d = self.d
            s = pgcd(n, d)
            return Fraction(n // s, d // s)
        if final:
            return self.decompose()
        # Pas de traitement spécifique nécessaire
        return self
예제 #30
0
    def traitement(self, final=False):
        """**traitement**\ (*object*,\ *self*)

        Finit la mise au même dénominatuer ou la simplicfication de la fraction.
        Si *final* est vrai, alors essaie de simplifier la fraction.

            >>> from pyromaths.classes.Fractions import Fraction
            >>> Fraction("3*4", "3*7", "r").traitement()
            Fraction(12, 21)
            >>> Fraction("3*4", "3*7", "s").traitement()
            Fraction(4, 7)
            >>> Fraction(12, 21).traitement()
            Fraction(12, 21)
            >>> Fraction(12, 21).traitement(True)
            Fraction("4*3", "7*3", "s")

        :param: final
        :type: boolean
        :rtype: Fraction
        """
        if self.code == "r":
            if isinstance(self.n, str): n = eval(self.n)
            else: n = self.n
            if isinstance(self.d, str): d = eval(self.d)
            else: d = self.d
            return Fraction(n, d)
        if self.code == "s":
            if isinstance(self.n, str): n = eval(self.n)
            else: n = self.n
            if isinstance(self.d, str): d = eval(self.d)
            else: d = self.d
            s = pgcd(n, d)
            return Fraction(n // s, d // s)
        if final:
            return self.decompose()
        "Pas de traitement spécifique nécessaire"
        return self
예제 #31
0
    def decompose(self):
        """**decompose**\ (*object*)

        Retourne une décomposition de la fraction afin de la simplifier

            >>> from pyromaths.classes.Fractions import Fraction
            >>> repr(Fraction.decompose(Fraction(8,20)))
            Fraction("2*4", "5*4", "s")

        :param type: Fraction
        :rtype: Fraction
        """
        if isinstance(self.n, str): self.n = eval(self.n)
        if isinstance(self.d, str): self.d = eval(self.d)
        conv = False
        if isinstance(self.n, SquareRoot):
            s = self.n.simplifie()
            if s != self.n:
                self.n = s
                conv = True
        if isinstance(self.d, SquareRoot):
            s = self.d.simplifie()
            if s != self.d:
                self.d = s
                conv = True
        if conv:
            return self
        if self.d == self.n:
            return 1
        else:
            lepgcd = pgcd(self.n, self.d)
            if lepgcd == 1:
                return self
            else:
                return Fraction("%r*%s" % (self.n // lepgcd, lepgcd),
                                "%r*%s" % (self.d // lepgcd, lepgcd), "s")
예제 #32
0
def simprad(liste):
    """Simplifie la fraction d'un angle en radians. Le paramètre est une liste d'entiers, pour représenter une fraction."""
    p = pgcd(liste[0],liste[1])
    return [f/p for f in liste]
예제 #33
0
def deg2rad(n):
    """Effectue la conversion de degrés entre 0 et 360° vers radians."""
    p = pgcd(n,180)
    return [n/p,180/p]
예제 #34
0
def simplifie(a):  # renvoie la fraction a simplifiee
    b = pgcd(a[0], a[1])
    if b != 1:
        return (a[0] // b, a[1] // b)
    else:
        return ''
예제 #35
0
    def __mul__(self, *others):
        """*object*\ .\ **__mul__**\ (*other*)

        ``p.__mul__(q)`` est équivalent à ``p * q``  calcule le produit deux fractions.

        *other* peut être une chaîne représentant une fraction, un entier ou un réel.

        >>> from pyromaths.classes.Fractions import Fraction
        >>> repr(Fraction(2,5) * Fraction(2,10))
        Fraction("2*2", "5*2*5", "s")
        >>> repr(Fraction(2,5) * 4)
        Fraction(8, 5)
        >>> repr(Fraction(63,20) * Fraction(8,27))
        Fraction("9*7*4*2", "4*5*9*3", "s")
        >>> repr(Fraction(24,12) * 12)
        Fraction("24*12", "12*1", "s")
        >>> repr(12*Fraction(24,12))
        Fraction("12*24", "1*12", "s")

        :param: other
        :type: Fraction ou string
        :rtype: Fraction ou string
        """
        from pyromaths.classes.PolynomesCollege import Polynome
        from pyromaths.classes.Polynome import Polynome as PolynomeLycee
        from .Racine import RacineDegre2

        if self == 0: return 0
        self = Fraction(
            self.n, self.d
        )  # Pour contourner le cas où self = Fraction(Fraction(1, 1), 1)
        lother, lnum, lden, details, var, traiter, lycee = [self], [self.n], [
            self.d
        ], 0, '', False, False
        for other in others:
            if other == 0:
                return 0
            elif isinstance(other, Polynome):
                var = other.var
                details = min(details, other.details)
                lother.append(other)
            elif isinstance(other, PolynomeLycee):
                var = other.var
                lycee = True
                lother.append(other)
            elif isinstance(other, (int, float)):
                lden.append(1)
                lnum.append(other)
                lother.append(Fraction(other))
            elif isinstance(other, Fraction):
                lother.append(other)
                if other.code: traiter = True
                try:
                    lden.append(eval(other.d))
                except TypeError:
                    lden.append(other.d)
                try:
                    lnum.append(eval(other.n))
                except TypeError:
                    lnum.append(other.n)
            elif isinstance(other, RacineDegre2):
                lother.append(other)
                lden.append(other.denominateur)
                lnum.append(other.numerateur)
            else:
                raise ValueError(u'Format incorrect : %s' % (other))
        if var:
            if lycee:
                self = PolynomeLycee({0: self}, var)
                return PolynomeLycee.__mul__(self, other)
            else:
                self = Polynome([[self, 0]], var, details)
                return Polynome.__mul__(self, *lother[1:])

        if traiter:
            lfrac = [repr(self.traitement())]
            for other in lother:
                lfrac.append(repr(other.traitement()))
            return "*".join(lfrac)
        try:
            self.d = eval(self.d)
        except TypeError:
            pass
        s = abs(
            pgcd(reduce(lambda x, y: x * y, lnum),
                 reduce(lambda x, y: x * y, lden)))
        if s == 1:
            return Fraction(reduce(lambda x, y: x * y, lnum),
                            reduce(lambda x, y: x * y, lden))
        lepgcd, num, den = s, [], []
        i = 0
        while i < len(lnum):
            if lepgcd == 1 or lepgcd in lnum:
                num.append("*".join(
                    [repr(lnum[k]) for k in range(i, len(lnum))]))
                break
            else:
                lepgcdtmp = pgcd(lnum[i], lepgcd)
                if lepgcdtmp != 1:
                    num.append("%r*%r" % (lepgcdtmp, lnum[i] // lepgcdtmp))
                else:
                    num.append("%r" % lnum[i])
                lepgcd = lepgcd / lepgcdtmp
                i += 1
        i, lepgcd = 0, s
        while i < len(lden):
            if lepgcd == 1 or lepgcd in lden:
                den.append("*".join(
                    [repr(lden[k]) for k in range(i, len(lden))]))
                break
            else:
                lepgcdtmp = pgcd(lden[i], lepgcd)
                if lepgcdtmp != 1:
                    den.append("%r*%r" % (lepgcdtmp, lden[i] // lepgcdtmp))
                else:
                    den.append("%r" % lden[i])
                lepgcd = lepgcd / lepgcdtmp
                i += 1
        num, den = "*".join(num), "*".join(den)
        while num[:2] == "1*":
            num = num[2:]
        while "*1*" in num:
            num = num.replace("*1*", "*", 1)
        if num[-2:] == "*1": num = num[:-2]
        if s == reduce(lambda x, y: x * y, lnum):
            # laisser un *1 ou 1* selon
            if self.n == 1: num = "1*" + num
            else: num += "*1"
        while den[:2] == "1*":
            den = den[2:]
        while "*1*" in den:
            den = den.replace("*1*", "*", 1)
        if den[-2:] == "*1": den = den[:-2]
        if s == reduce(lambda x, y: x * y, lden):
            # laisser un *1
            if self.d == 1: den = "1*" + den
            else: den += "*1"

        if "*" in num: num = num.strip()
        if "*" in den: den = den.strip()
        return Fraction(num, den, "s")
예제 #36
0
    def __str__(self):
        r"""**str**\ (*object*)

        Renvoie une version LaTeX de la :class:`Fraction`.
            >>> from pyromaths.classes.Fractions import Fraction
            >>> str(Fraction(8,1))
            8
            >>> str(Fraction(5,6))
            \dfrac{5}{6}
            >>> str(Fraction('-5*2', '3*2', 'r'))
            \dfrac{-5_{\times 2}}{3_{\times 2}}
            >>> str(Fraction('5*-7*2', '11*2*5', 's'))
            \dfrac{\cancel{5}\times \left( -7\right) \times \cancel{2}}{11\times \cancel{2}\times \cancel{5}}
            >>> str(Fraction('-144', '22', 's'))
            \dfrac{-72\times \cancel{2}}{11\times \cancel{2}}
            >>> from pyromaths.classes.SquareRoot import SquareRoot
            >>> str(Fraction(SquareRoot([[-10, None], [-1, 80]]), -2))
            \dfrac{-10-\sqrt{80}}{-2}
            >>> str(Fraction(SquareRoot([[-10, None], [-4, 5]]), -2, 's'))
            \dfrac{\left( 5+2\,\sqrt{5}\right) \times \cancel{-2}}{1\times \cancel{-2}}

        :rtype: string
        """
        from pyromaths.outils.Priorites3 import splitting
        #=======================================================================
        # print (repr(self))
        #=======================================================================
        if self.n == 0 or self.n == '0':
            return '0'
        lnum, lden = [], []
        if isinstance(self.n, str): lnum = splitting(self.n)
        if isinstance(self.d, str): lden = splitting(self.d)
        if len(lnum) == 1: self.n, lnum = eval(self.n), []
        if len(lden) == 1: self.d, lden = eval(self.d), []
        if self.d == 1:
            return (str(self.n), texify([lnum])[0])[lnum != []]
        if self.code == "r":
            # lnum et lden doivent être définis et se terminer par [..., '*', valeur]
            if not lnum or not lden or lnum[-2:] != lden[-2:]:
                raise ValueError(
                    u'Mauvais usage de l\'étiquettes "r" dans %r' % self)
            lden[-2], lden[-1], lnum[-2], lnum[-1] = [lden[-2], 'indice'], [
                lden[-1], 'indice'
            ], [lnum[-2], 'indice'], [lnum[-1], 'indice']
            return '\\dfrac{%s}{%s}' % (texify([lnum])[0], texify([lden])[0])
        if self.code == "s":
            if isinstance(self.n, (int, float, SquareRoot)) and isinstance(
                    self.d, (int, float, SquareRoot)):
                lepgcd = pgcd(self.n, self.d)
                lnum, lden = [
                    repr(self.n // lepgcd), '*', [str(lepgcd), 'cancel']
                ], [repr(self.d // lepgcd), '*', [str(lepgcd), 'cancel']]
            else:
                for i in range(len(lnum)):
                    if lnum[i] != '*' and lden.count(lnum[i]):
                        # On doit simplifier la fraction par ce nombre
                        j = lden.index(lnum[i])
                        lden[j] = [lden[j], 'cancel']
                        lnum[i] = [lnum[i], 'cancel']
            return '\\dfrac{%s}{%s}' % (texify([lnum])[0], texify([lden])[0])
        s = r'\dfrac'
        s += '{%s}' % (self.n, texify([lnum])[0])[lnum != []]
        s += '{%s}' % (self.d, texify([lden])[0])[lden != []]
        return s
예제 #37
0
    def __mul__(self, *others):
        """*object*\ .\ **__mul__**\ (*other*)

        ``p.__mul__(q)`` est équivalent à ``p * q``  calcule le produit deux fractions.

        *other* peut être une chaîne représentant une fraction, un entier ou un réel.

        >>> from pyromaths.classes.Fractions import Fraction
        >>> Fraction(2,5) * Fraction(2,10)
        Fraction("2*2", "5*2*5", "s")
        >>> Fraction(2,5) * 4
        Fraction(8, 5)
        >>> Fraction(63,20) * Fraction(8,27)
        Fraction("9*7*4*2", "4*5*9*3", "s")
        >>> Fraction(24,12) * 12
        Fraction("24*12", "12*1", "s")
        >>> 12*Fraction(24,12)
        Fraction("12*24", "1*12", "s")

        :param: other
        :type: Fraction ou string
        :rtype: Fraction ou string
        """
        from pyromaths.classes.PolynomesCollege import Polynome
        from pyromaths.classes.Polynome import Polynome as PolynomeLycee
        from .Racine import RacineDegre2

        if self == 0: return 0
        self = Fraction(self.n, self.d)  # Pour contourner le cas où self = Fraction(Fraction(1, 1), 1)
        lother, lnum, lden, details, var, traiter, lycee = [self], [self.n], [self.d], 0, '', False, False
        for other in others:
            if other == 0:
                return 0
            elif isinstance(other, Polynome):
                var = other.var
                details = min(details, other.details)
                lother.append(other)
            elif isinstance(other, PolynomeLycee):
                var = other.var
                lycee = True
                lother.append(other)
            elif isinstance(other, (int, float)):
                lden.append(1)
                lnum.append(other)
                lother.append(Fraction(other))
            elif isinstance(other, Fraction):
                lother.append(other)
                if other.code: traiter = True
                try: lden.append(eval(other.d))
                except TypeError: lden.append(other.d)
                try: lnum.append(eval(other.n))
                except TypeError: lnum.append(other.n)
            elif isinstance(other, RacineDegre2):
                lother.append(other)
                lden.append(other.denominateur)
                lnum.append(other.numerateur)
            else:
                raise ValueError(u'Format incorrect : %s' % (other))
        if var:
            if lycee:
                self = PolynomeLycee({0:self}, var)
                return PolynomeLycee.__mul__(self, other)
            else:
                self = Polynome([[self, 0]], var, details)
                return Polynome.__mul__(self, *lother[1:])

        if traiter:
            lfrac = [repr(self.traitement())]
            for other in lother:
                lfrac.append(repr(other.traitement()))
            return "*".join(lfrac)
        try: self.d = eval(self.d)
        except TypeError: pass
        s = abs(pgcd(reduce(lambda x, y: x * y, lnum), reduce(lambda x, y: x * y, lden)))
        if s == 1: return Fraction(reduce(lambda x, y: x * y, lnum), reduce(lambda x, y: x * y, lden))
        lepgcd, num, den = s, [], []
        i = 0
        while i < len(lnum):
            if lepgcd == 1 or lepgcd in lnum:
                num.append("*".join([repr(lnum[k]) for k in range(i, len(lnum))]))
                break
            else:
                lepgcdtmp = pgcd(lnum[i], lepgcd)
                if lepgcdtmp != 1: num.append("%r*%r" % (lepgcdtmp, lnum[i] // lepgcdtmp))
                else: num.append("%r" % lnum[i])
                lepgcd = lepgcd / lepgcdtmp
                i += 1
        i, lepgcd = 0, s
        while i < len(lden):
            if lepgcd == 1 or lepgcd in lden:
                den.append("*".join([repr(lden[k]) for k in range(i, len(lden))]))
                break
            else:
                lepgcdtmp = pgcd(lden[i], lepgcd)
                if lepgcdtmp != 1: den.append("%r*%r" % (lepgcdtmp, lden[i] // lepgcdtmp))
                else: den.append("%r" % lden[i])
                lepgcd = lepgcd / lepgcdtmp
                i += 1
        num, den = "*".join(num), "*".join(den)
        while num[:2] == "1*": num = num[2:]
        while "*1*" in num: num = num.replace("*1*", "*", 1)
        if num[-2:] == "*1": num = num[:-2]
        if s == reduce(lambda x, y: x * y, lnum):
            # laisser un *1 ou 1* selon
            if self.n == 1: num = "1*" + num
            else: num += "*1"
        while den[:2] == "1*": den = den[2:]
        while "*1*" in den: den = den.replace("*1*", "*" , 1)
        if den[-2:] == "*1": den = den[:-2]
        if s == reduce(lambda x, y: x * y, lden):
            # laisser un *1
            if self.d == 1: den = "1*" + den
            else: den += "*1"

        if "*" in num: num = num.strip()
        if "*" in den: den = den.strip()
        return Fraction(num, den, "s")
예제 #38
0
def diagramme_tex(typed=2, val=[[], []], aide=0):
    """Génère un diagramme en bâtons (type 1), circulaire (type2) ou semi-circulaire (type3) à partir des fréquences (liste val[1]) et son tableau de calculs."""
    diag = ""

    couleur = [
        "AliceBlue", "Bisque", "PaleGreen", "Thistle", "LightGray", "Khaki",
        "LightBlue", "LightSalmon", "PaleGoldenrod", "PapayaWhip", "Plum",
        "Gainsboro"
    ]

    if typed == 1:  # Diagramme en bâtons

        grad = len(val[1]) + 1
        diag += u"\\begin{pspicture}(-1,-1)(" + str(grad) + ",11)\n"
        diag += u"\\psset{xunit=1cm,yunit=1cm}\n"
        diag += u"\\psgrid[subgriddiv=1,griddots=5,gridlabels=0](" + str(
            grad) + ",11)\n"
        diag += u"\\psaxes[Dx=1,dx=1,Dy=10,dy=1]{->}(0,0)(" + str(
            grad) + ",11)\n"

        for f in range(len(val[1])):
            diag += u"\\psline[linewidth=0.1,linecolor=green](" + val[0][
                f + 1] + ",0)(" + val[0][f + 1] + "," + str(
                    val[1][f] / 10.0) + ")\n"

        diag += u"\\rput(0,11.2){\\small Fréquences (\\%)}\n"
        diag += u"\\rput(" + str(grad +
                                 0.5) + ",0){\\small " + val[0][0] + "}\n"
        diag += u"\\end{pspicture}\n"

    elif typed == 2:  # Diagramme circulaire
        grad = len(val[1])
        diag += u"\\begin{pspicture}(-3,-3)(3,3)\n"
        diag_texte = ""

        debut = 0
        fin = round(val[1][0] * 3.6, 0)
        liste_fin = [
            fin
        ]  # Pour éviter d'avoir les pointillés superposés sur des lignes

        for v in range(len(val[1]) - 1):
            diag += u"\\pswedge[fillstyle=solid,fillcolor=" + couleur[
                v % 12] + "](0,0){3}{" + str(debut) + "}{" + str(fin) + "}\n"
            diag_texte += u"\\rput[r]{" + str(
                (debut + fin) / 2.0) + "}(" + str(
                    3 * round(cos(radians(
                        (debut + fin) / 2.0)), 2)) + "," + str(
                            3 * round(sin(radians((debut + fin) / 2.0)), 2)
                        ) + "){\\small \\bfseries{" + val[0][v + 1] + "}}\n"
            debut = fin
            fin += round(val[1][v + 1] * 3.6, 0)
            liste_fin.append(fin)
        diag += u"\\pswedge[fillstyle=solid,fillcolor=" + couleur[
            (len(val[1]) - 1) % 12] + "](0,0){3}{" + str(debut) + "}{360}\n"
        diag_texte += u"\\rput[r]{" + str((debut + fin) / 2.0) + "}(" + str(
            3 * round(cos(radians((debut + fin) / 2.0)), 2)) + "," + str(
                3 * round(sin(radians((debut + fin) / 2.0)),
                          2)) + "){\\small \\bfseries{" + val[0][-1] + "}}\n"

        if aide != 0:
            temp = [int(3.6 * v) for v in val[1]]
            temp2 = [
                pgcd(temp[i], temp[i + 1]) for i in range(len(val[1]) - 1)
            ]
            temp2.sort()
            ecart = temp2[0]
            angle = ecart

            while angle < 360:
                if angle not in liste_fin:
                    diag += u"\\psline[linestyle=dashed,linecolor=gray](0,0)(" + str(
                        3 * round(cos(radians(angle)), 2)) + "," + str(
                            3 * round(sin(radians(angle)), 2)) + ")\n"
                angle += ecart

        diag += diag_texte
        diag += u"\\end{pspicture}\n"

    elif typed == 3:  # Diagramme semi-circulaire
        grad = len(val[1])
        diag += u"\\begin{pspicture}(0,0)(3,3)\n"
        diag_texte = ""

        debut = 0
        fin = round(val[1][0] * 1.8, 0)
        liste_fin = [
            fin
        ]  # Pour éviter d'avoir les pointillés superposés sur des lignes

        for v in range(len(val[1]) - 1):
            diag += u"\\pswedge[fillstyle=solid,fillcolor=" + couleur[
                v % 12] + "](0,0){3}{" + str(debut) + "}{" + str(fin) + "}\n"
            diag_texte += u"\\rput[r]{" + str(
                (debut + fin) /
                2.0) + "}(" + str(3 * round(cos(radians(
                    (debut + fin) / 2.0)), 2)) + "," + str(
                        3 * round(sin(radians((debut + fin) / 2.0)), 2)
                    ) + "){\\small \\bfseries{" + val[0][
                        v +
                        1] + "}}\n"  # FIX problème hauteur textes superposés
            debut = fin
            fin += round(val[1][v + 1] * 1.8, 0)
            liste_fin.append(fin)
        diag += u"\\pswedge[fillstyle=solid,fillcolor=" + couleur[
            (len(val[1]) - 1) % 12] + "](0,0){3}{" + str(debut) + "}{180}\n"
        diag_texte += u"\\rput[r]{" + str((debut + fin) / 2.0) + "}(" + str(
            3 * round(cos(radians((debut + fin) / 2.0)), 2)) + "," + str(
                3 * round(sin(radians((debut + fin) / 2.0)),
                          2)) + "){\\small \\bfseries{" + val[0][-1] + "}}\n"

        if aide != 0:
            temp = [int(1.8 * v) for v in val[1]]
            temp2 = [
                pgcd(temp[i], temp[i + 1]) for i in range(len(val[1]) - 1)
            ]
            temp2.sort()
            ecart = temp2[0]
            angle = ecart

            while angle < 180:
                if angle not in liste_fin:
                    diag += u"\\psline[linestyle=dashed,linecolor=gray](0,0)(" + str(
                        3 * round(cos(radians(angle)), 2)) + "," + str(
                            3 * round(sin(radians(angle)), 2)) + ")\n"
                angle += ecart

        diag += diag_texte
        diag += u"\\end{pspicture}\n"

    return diag
예제 #39
0
def exo_ages():
    """Exercice sur la répartition des âges dans une population."""
    global exo, cor

    # Partitions de 20
    partitions = [[4, 4, 4, 4, 4], [3, 4, 4, 4, 5], [3, 3, 4, 5, 5],
                  [2, 4, 4, 5, 5], [2, 3, 5, 5, 5], [1, 4, 5, 5, 5],
                  [3, 3, 4, 4, 6], [2, 4, 4, 4, 6], [3, 3, 3, 5, 6],
                  [2, 3, 4, 5, 6], [1, 4, 4, 5, 6], [2, 2, 5, 5, 6],
                  [1, 3, 5, 5, 6], [2, 3, 3, 6, 6], [2, 2, 4, 6, 6],
                  [1, 3, 4, 6, 6], [1, 2, 5, 6, 6], [1, 1, 6, 6, 6],
                  [3, 3, 3, 4, 7], [2, 3, 4, 4, 7], [1, 4, 4, 4, 7],
                  [2, 3, 3, 5, 7], [2, 2, 4, 5, 7], [1, 3, 4, 5, 7],
                  [1, 2, 5, 5, 7], [2, 2, 3, 6, 7], [1, 3, 3, 6, 7],
                  [1, 2, 4, 6, 7], [1, 1, 5, 6, 7], [2, 2, 2, 7, 7],
                  [1, 2, 3, 7, 7], [1, 1, 4, 7, 7], [3, 3, 3, 3, 8],
                  [2, 3, 3, 4, 8], [2, 2, 4, 4, 8], [1, 3, 4, 4, 8],
                  [2, 2, 3, 5, 8], [1, 3, 3, 5, 8], [1, 2, 4, 5, 8],
                  [1, 1, 5, 5, 8], [2, 2, 2, 6, 8], [1, 2, 3, 6, 8],
                  [1, 1, 4, 6, 8], [1, 2, 2, 7, 8], [1, 1, 3, 7, 8],
                  [1, 1, 2, 8, 8], [2, 3, 3, 3, 9], [2, 2, 3, 4, 9],
                  [1, 3, 3, 4, 9], [1, 2, 4, 4, 9], [2, 2, 2, 5, 9],
                  [1, 2, 3, 5, 9], [1, 1, 4, 5, 9], [1, 2, 2, 6, 9],
                  [1, 1, 3, 6, 9], [1, 1, 2, 7, 9], [1, 1, 1, 8, 9],
                  [2, 2, 3, 3, 10], [1, 3, 3, 3, 10], [2, 2, 2, 4, 10],
                  [1, 2, 3, 4, 10], [1, 1, 4, 4, 10], [1, 2, 2, 5, 10],
                  [1, 1, 3, 5, 10], [1, 1, 2, 6, 10], [1, 1, 1, 7, 10],
                  [2, 2, 2, 3, 11], [1, 2, 3, 3, 11], [1, 2, 2, 4, 11],
                  [1, 1, 3, 4, 11], [1, 1, 2, 5, 11], [1, 1, 1, 6, 11],
                  [2, 2, 2, 2, 12], [1, 2, 2, 3, 12], [1, 1, 3, 3, 12],
                  [1, 1, 2, 4, 12], [1, 1, 1, 5, 12], [1, 2, 2, 2, 13],
                  [1, 1, 2, 3, 13], [1, 1, 1, 4, 13], [1, 1, 2, 2, 14],
                  [1, 1, 1, 3, 14], [1, 1, 1, 2, 15], [1, 1, 1, 1, 16]]

    choix_diagramme = random.randint(0, 1)
    if choix_diagramme == 0:
        diagramme_texte = _("circulaire")
    else:
        diagramme_texte = _("semi-circulaire")
    hasard = partitions[random.randint(0, len(partitions) - 1)]
    frequences = [5 * v for v in hasard]
    random.shuffle(frequences)

    population = 20 * random.randint(100, 2000)

    diagramme = diagramme_tex(choix_diagramme + 2, [[
        _(u"Ages"),
        _(u"<20 ans"),
        _("20 - 40 ans"),
        _("40 - 60 ans"),
        _("60 - 80 ans"),
        _(u">80 ans")
    ], frequences], 1)
    exo.append(u"\\begin{center}")
    cor.append(u"\\begin{center}")
    exo.append(diagramme)
    cor.append(diagramme)
    exo.append(u"\\end{center}")
    cor.append(u"\\end{center}")
    exo.append(
        _(u"Le diagramme ") + diagramme_texte +
        _(u" ci-dessus représente les différentes fréquences des classes d'âges dans une certaine région.\\par"
          ))
    cor.append(
        _(u"Le diagramme ") + diagramme_texte +
        _(u" ci-dessus représente les différentes fréquences des classes d'âges dans une certaine région.\\par"
          ))
    exo.append("\\begin{enumerate}")
    cor.append("\\begin{enumerate}")
    exo.append(_(u"\\item Calculer les fréquences de chaque classe d'âges."))
    cor.append(
        _(u"\\item Calculer les fréquences de chaque classe d'âges.\\par"))

    titres = [
        _(u"Classes d'âges"),
        _(u"$0 \\leq n \\leq 20$"),
        _(u"$20 \\leq n \\leq 40$"),
        _(u"$40 \\leq n \\leq 60$"),
        _(u"$60 \\leq n \\leq 80$"),
        _(u"$80 \\geq n$"),
    ]

    liste_pgcd = [
        pgcd(frequences[i], frequences[i + 1])
        for i in range(len(frequences) - 2)
    ]
    liste_pgcd.sort()
    pourcent = liste_pgcd[0]
    parts = 100 / pourcent
    effectifs = [f * population / 100 for f in frequences]

    cor.append(
        _(u"Le diagramme ") + diagramme_texte + _(u" est partagé en ") +
        str(parts) +
        _(u" parts symbolisées par des lignes grises en pointillés.\\par"))
    cor.append(
        _(u"On en déduit que chacune de ces parts représente $\\dfrac{100}{") +
        str(parts) + "}=" + str(pourcent) +
        _(u"\\%$, puis en comptant le nombre de parts dans chaque classe, on obtient le tableau suivant :\\par"
          ))
    cor.append("\\end{enumerate}")
    cor.append(
        tableau_tex(titres, ">{\\centering}p{2.2cm}", 0, 1, [[], frequences]))
    cor.append("\\begin{enumerate}")
    exo.append(
        _(u"\\item Sachant que la population étudiée est composée de ") +
        str(population) +
        _(u" personnes, calculer les effectifs de chaque classe d'âges."))
    cor.append(
        _(u"\\item[$\\blacktriangleright$\\textbf{2.}] Sachant que la population étudiée est composée de "
          ) + str(population) +
        _(u" personnes, calculer les effectifs de chaque classe d'âges.\\par"))

    cor.append(
        _(u"Sachant que la classe des moins de vingt ans est composée de ") +
        str(frequences[0]) + u" \\% de " + str(population) +
        _(u" personnes, on peut calculer l'effectif concerné :\\par"))
    cor.append(u"$\\dfrac{" + str(frequences[0]) + u" \\times " +
               str(population) + u"}{100}=" + str(effectifs[0]) + u"$.\\par")
    cor.append(
        _(u"Avec le même type de calcul, on obtient les effectifs des autres classes, résumés dans le tableau ci-dessous :"
          ))
    cor.append("\\end{enumerate}")
    cor.append(
        tableau_tex(titres, ">{\\centering}p{2.2cm}", 1, 1,
                    [effectifs, frequences]))

    exo.append("\n\\end{enumerate}")

    return False
예제 #40
0
def deg2rad(n):
    """Effectue la conversion de degrés entre 0 et 360° vers radians."""
    p = pgcd(n, 180)
    return [n / p, 180 / p]
예제 #41
0
def diagramme_tex(typed=2, val=[[], []], aide=0):
    """Génère un diagramme en bâtons (type 1), circulaire (type2) ou semi-circulaire (type3) à partir des fréquences (liste val[1]) et son tableau de calculs."""
    diag = ""

    couleur = [
        "AliceBlue",
        "Bisque",
        "PaleGreen",
        "Thistle",
        "LightGray",
        "Khaki",
        "LightBlue",
        "LightSalmon",
        "PaleGoldenrod",
        "PapayaWhip",
        "Plum",
        "Gainsboro",
    ]

    if typed == 1:  # Diagramme en bâtons

        grad = len(val[1]) + 1
        diag += u"\\begin{pspicture}(-1,-1)(" + str(grad) + ",11)\n"
        diag += u"\\psset{xunit=1cm,yunit=1cm}\n"
        diag += u"\\psgrid[subgriddiv=1,griddots=5,gridlabels=0](" + str(grad) + ",11)\n"
        diag += u"\\psaxes[Dx=1,dx=1,Dy=10,dy=1]{->}(0,0)(" + str(grad) + ",11)\n"

        for f in range(len(val[1])):
            diag += (
                u"\\psline[linewidth=0.1,linecolor=green]("
                + val[0][f + 1]
                + ",0)("
                + val[0][f + 1]
                + ","
                + str(val[1][f] / 10.0)
                + ")\n"
            )

        diag += u"\\rput(0,11.2){\\small Fréquences (\\%)}\n"
        diag += u"\\rput(" + str(grad + 0.5) + ",0){\\small " + val[0][0] + "}\n"
        diag += u"\\end{pspicture}\n"

    elif typed == 2:  # Diagramme circulaire
        grad = len(val[1])
        diag += u"\\begin{pspicture}(-3,-3)(3,3)\n"
        diag_texte = ""

        debut = 0
        fin = round(val[1][0] * 3.6, 0)
        liste_fin = [fin]  # Pour éviter d'avoir les pointillés superposés sur des lignes

        for v in range(len(val[1]) - 1):
            diag += (
                u"\\pswedge[fillstyle=solid,fillcolor="
                + couleur[v % 12]
                + "](0,0){3}{"
                + str(debut)
                + "}{"
                + str(fin)
                + "}\n"
            )
            diag_texte += (
                u"\\rput[r]{"
                + str((debut + fin) / 2.0)
                + "}("
                + str(3 * round(cos(radians((debut + fin) / 2.0)), 2))
                + ","
                + str(3 * round(sin(radians((debut + fin) / 2.0)), 2))
                + "){\\small \\bfseries{"
                + val[0][v + 1]
                + "}}\n"
            )
            debut = fin
            fin += round(val[1][v + 1] * 3.6, 0)
            liste_fin.append(fin)
        diag += (
            u"\\pswedge[fillstyle=solid,fillcolor="
            + couleur[(len(val[1]) - 1) % 12]
            + "](0,0){3}{"
            + str(debut)
            + "}{360}\n"
        )
        diag_texte += (
            u"\\rput[r]{"
            + str((debut + fin) / 2.0)
            + "}("
            + str(3 * round(cos(radians((debut + fin) / 2.0)), 2))
            + ","
            + str(3 * round(sin(radians((debut + fin) / 2.0)), 2))
            + "){\\small \\bfseries{"
            + val[0][-1]
            + "}}\n"
        )

        if aide != 0:
            temp = [int(3.6 * v) for v in val[1]]
            temp2 = [pgcd(temp[i], temp[i + 1]) for i in range(len(val[1]) - 1)]
            temp2.sort()
            ecart = temp2[0]
            angle = ecart

            while angle < 360:
                if angle not in liste_fin:
                    diag += (
                        u"\\psline[linestyle=dashed,linecolor=gray](0,0)("
                        + str(3 * round(cos(radians(angle)), 2))
                        + ","
                        + str(3 * round(sin(radians(angle)), 2))
                        + ")\n"
                    )
                angle += ecart

        diag += diag_texte
        diag += u"\\end{pspicture}\n"

    elif typed == 3:  # Diagramme semi-circulaire
        grad = len(val[1])
        diag += u"\\begin{pspicture}(0,0)(3,3)\n"
        diag_texte = ""

        debut = 0
        fin = round(val[1][0] * 1.8, 0)
        liste_fin = [fin]  # Pour éviter d'avoir les pointillés superposés sur des lignes

        for v in range(len(val[1]) - 1):
            diag += (
                u"\\pswedge[fillstyle=solid,fillcolor="
                + couleur[v % 12]
                + "](0,0){3}{"
                + str(debut)
                + "}{"
                + str(fin)
                + "}\n"
            )
            diag_texte += (
                u"\\rput[r]{"
                + str((debut + fin) / 2.0)
                + "}("
                + str(3 * round(cos(radians((debut + fin) / 2.0)), 2))
                + ","
                + str(3 * round(sin(radians((debut + fin) / 2.0)), 2))
                + "){\\small \\bfseries{"
                + val[0][v + 1]
                + "}}\n"
            )  # FIX problème hauteur textes superposés
            debut = fin
            fin += round(val[1][v + 1] * 1.8, 0)
            liste_fin.append(fin)
        diag += (
            u"\\pswedge[fillstyle=solid,fillcolor="
            + couleur[(len(val[1]) - 1) % 12]
            + "](0,0){3}{"
            + str(debut)
            + "}{180}\n"
        )
        diag_texte += (
            u"\\rput[r]{"
            + str((debut + fin) / 2.0)
            + "}("
            + str(3 * round(cos(radians((debut + fin) / 2.0)), 2))
            + ","
            + str(3 * round(sin(radians((debut + fin) / 2.0)), 2))
            + "){\\small \\bfseries{"
            + val[0][-1]
            + "}}\n"
        )

        if aide != 0:
            temp = [int(1.8 * v) for v in val[1]]
            temp2 = [pgcd(temp[i], temp[i + 1]) for i in range(len(val[1]) - 1)]
            temp2.sort()
            ecart = temp2[0]
            angle = ecart

            while angle < 180:
                if angle not in liste_fin:
                    diag += (
                        u"\\psline[linestyle=dashed,linecolor=gray](0,0)("
                        + str(3 * round(cos(radians(angle)), 2))
                        + ","
                        + str(3 * round(sin(radians(angle)), 2))
                        + ")\n"
                    )
                angle += ecart

        diag += diag_texte
        diag += u"\\end{pspicture}\n"

    return diag
예제 #42
0
def exo_ages():
    """Exercice sur la répartition des âges dans une population."""
    global exo, cor

    # Partitions de 20
    partitions = [
        [4, 4, 4, 4, 4],
        [3, 4, 4, 4, 5],
        [3, 3, 4, 5, 5],
        [2, 4, 4, 5, 5],
        [2, 3, 5, 5, 5],
        [1, 4, 5, 5, 5],
        [3, 3, 4, 4, 6],
        [2, 4, 4, 4, 6],
        [3, 3, 3, 5, 6],
        [2, 3, 4, 5, 6],
        [1, 4, 4, 5, 6],
        [2, 2, 5, 5, 6],
        [1, 3, 5, 5, 6],
        [2, 3, 3, 6, 6],
        [2, 2, 4, 6, 6],
        [1, 3, 4, 6, 6],
        [1, 2, 5, 6, 6],
        [1, 1, 6, 6, 6],
        [3, 3, 3, 4, 7],
        [2, 3, 4, 4, 7],
        [1, 4, 4, 4, 7],
        [2, 3, 3, 5, 7],
        [2, 2, 4, 5, 7],
        [1, 3, 4, 5, 7],
        [1, 2, 5, 5, 7],
        [2, 2, 3, 6, 7],
        [1, 3, 3, 6, 7],
        [1, 2, 4, 6, 7],
        [1, 1, 5, 6, 7],
        [2, 2, 2, 7, 7],
        [1, 2, 3, 7, 7],
        [1, 1, 4, 7, 7],
        [3, 3, 3, 3, 8],
        [2, 3, 3, 4, 8],
        [2, 2, 4, 4, 8],
        [1, 3, 4, 4, 8],
        [2, 2, 3, 5, 8],
        [1, 3, 3, 5, 8],
        [1, 2, 4, 5, 8],
        [1, 1, 5, 5, 8],
        [2, 2, 2, 6, 8],
        [1, 2, 3, 6, 8],
        [1, 1, 4, 6, 8],
        [1, 2, 2, 7, 8],
        [1, 1, 3, 7, 8],
        [1, 1, 2, 8, 8],
        [2, 3, 3, 3, 9],
        [2, 2, 3, 4, 9],
        [1, 3, 3, 4, 9],
        [1, 2, 4, 4, 9],
        [2, 2, 2, 5, 9],
        [1, 2, 3, 5, 9],
        [1, 1, 4, 5, 9],
        [1, 2, 2, 6, 9],
        [1, 1, 3, 6, 9],
        [1, 1, 2, 7, 9],
        [1, 1, 1, 8, 9],
        [2, 2, 3, 3, 10],
        [1, 3, 3, 3, 10],
        [2, 2, 2, 4, 10],
        [1, 2, 3, 4, 10],
        [1, 1, 4, 4, 10],
        [1, 2, 2, 5, 10],
        [1, 1, 3, 5, 10],
        [1, 1, 2, 6, 10],
        [1, 1, 1, 7, 10],
        [2, 2, 2, 3, 11],
        [1, 2, 3, 3, 11],
        [1, 2, 2, 4, 11],
        [1, 1, 3, 4, 11],
        [1, 1, 2, 5, 11],
        [1, 1, 1, 6, 11],
        [2, 2, 2, 2, 12],
        [1, 2, 2, 3, 12],
        [1, 1, 3, 3, 12],
        [1, 1, 2, 4, 12],
        [1, 1, 1, 5, 12],
        [1, 2, 2, 2, 13],
        [1, 1, 2, 3, 13],
        [1, 1, 1, 4, 13],
        [1, 1, 2, 2, 14],
        [1, 1, 1, 3, 14],
        [1, 1, 1, 2, 15],
        [1, 1, 1, 1, 16],
    ]

    choix_diagramme = random.randint(0, 1)
    if choix_diagramme == 0:
        diagramme_texte = "circulaire"
    else:
        diagramme_texte = "semi-circulaire"
    hasard = partitions[random.randint(0, len(partitions) - 1)]
    frequences = [5 * v for v in hasard]
    random.shuffle(frequences)

    population = 20 * random.randint(100, 2000)

    diagramme = diagramme_tex(
        choix_diagramme + 2,
        [[u"Ages", u"<20 ans", "20 - 40 ans", "40 - 60 ans", "60 - 80 ans", u">80 ans"], frequences],
        1,
    )
    exo.append(u"\\begin{center}")
    cor.append(u"\\begin{center}")
    exo.append(diagramme)
    cor.append(diagramme)
    exo.append(u"\\end{center}")
    cor.append(u"\\end{center}")
    exo.append(
        u"Le diagramme "
        + diagramme_texte
        + u" ci-dessus représente les différentes fréquences des classes d'âges dans une certaine région.\\par"
    )
    cor.append(
        u"Le diagramme "
        + diagramme_texte
        + u" ci-dessus représente les différentes fréquences des classes d'âges dans une certaine région.\\par"
    )
    exo.append("\\begin{enumerate}")
    cor.append("\\begin{enumerate}")
    exo.append(u"\\item Calculer les fréquences de chaque classe d'âges.")
    cor.append(u"\\item Calculer les fréquences de chaque classe d'âges.\\par")

    titres = [
        u"Classes d'âges",
        u"$0 \\leq n \\leq 20$",
        u"$20 \\leq n \\leq 40$",
        u"$40 \\leq n \\leq 60$",
        u"$60 \\leq n \\leq 80$",
        u"$80 \\geq n$",
    ]

    liste_pgcd = [pgcd(frequences[i], frequences[i + 1]) for i in range(len(frequences) - 2)]
    liste_pgcd.sort()
    pourcent = liste_pgcd[0]
    parts = 100 / pourcent
    effectifs = [f * population / 100 for f in frequences]

    cor.append(
        u"Le diagramme "
        + diagramme_texte
        + u" est partagé en "
        + str(parts)
        + u" parts symbolisées par des lignes grises en pointillés.\\par"
    )
    cor.append(
        u"On en déduit que chacune de ces parts représente $\\dfrac{100}{"
        + str(parts)
        + "}="
        + str(pourcent)
        + u"\\%$, puis en comptant le nombre de parts dans chaque classe, on obtient le tableau suivant :\\par"
    )
    cor.append("\\end{enumerate}")
    cor.append(tableau_tex(titres, ">{\\centering}p{2.2cm}", 0, 1, [[], frequences]))
    cor.append("\\begin{enumerate}")
    exo.append(
        u"\\item Sachant que la population étudiée est composée de "
        + str(population)
        + u" personnes, calculer les effectifs de chaque classe d'âges."
    )
    cor.append(
        u"\\item[$\\blacktriangleright$\\textbf{2.}] Sachant que la population étudiée est composée de "
        + str(population)
        + u" personnes, calculer les effectifs de chaque classe d'âges.\\par"
    )

    cor.append(
        u"Sachant que la classe des moins de vingt ans est composée de "
        + str(frequences[0])
        + u" \\% de "
        + str(population)
        + u" personnes, on peut calculer l'effectif concerné :\\par"
    )
    cor.append(
        u"$\\dfrac{" + str(frequences[0]) + u" \\times " + str(population) + u"}{100}=" + str(effectifs[0]) + u"$.\\par"
    )
    cor.append(
        u"Avec le même type de calcul, on obtient les effectifs des autres classes, résumés dans le tableau ci-dessous :"
    )
    cor.append("\\end{enumerate}")
    cor.append(tableau_tex(titres, ">{\\centering}p{2.2cm}", 1, 1, [effectifs, frequences]))

    exo.append("\n\\end{enumerate}")

    return False
예제 #43
0
def simprad(liste):
    """Simplifie la fraction d'un angle en radians. Le paramètre est une liste d'entiers, pour représenter une fraction."""
    p = pgcd(liste[0], liste[1])
    return [f / p for f in liste]
예제 #44
0
def Arithmetique():
    """Exercice de décomposition de nombres en facteurs premiers, puis de
    recherche du PGCD et du PPCM, et d'applications aux fractions"""

    # ## Question 1
    exo = ["\\exercice", '\\begin{enumerate}', u"\\item Donner la décomposition" + 
            u" en facteurs premiers des nombres suivants, et préciser quand il" + 
            u" s\'agit d\'un nombre premier :\\par"]
    cor = ["\\exercice*", '\\begin{enumerate}', u"\\item Donner la décomposition"
            + u" en facteurs premiers des nombres suivants, et préciser quand il"
            + u" s\'agit d\'un nombre premier :\\par"]

    prime = premiers[randint(10, 167)]

    fauxpgcd = randint(1, 101)
    fauxpgcdfactor = factoriseTex(fauxpgcd)[0]

    complementaires = [randint(6, 50), randint(6, 50)]
    pgcdcompl = pgcd(complementaires[0], complementaires[1])
    pgcdcomplfact = factoriseTex(pgcdcompl)[0]

    if pgcdcompl != 1:
        facteurs = pgcdcomplfact + fauxpgcdfactor
        facteurs.sort()
    else:
        facteurs = fauxpgcdfactor

    autresnombres = [randint(51, 999), randint(51, 999)]

    listenombres = [prime, complementaires[0] * fauxpgcd, complementaires[1] * 
            fauxpgcd, ] + autresnombres
    melange = [prime, complementaires[0] * fauxpgcd, complementaires[1] * 
            fauxpgcd, ] + autresnombres
    shuffle(melange)

    exo.append(decimaux(melange[0]) + " ; " + decimaux(melange[1]) + " ; " + 
            decimaux(melange[2]) + " ; " + decimaux(melange[3]) + " ; " + 
            decimaux(melange[4]) + " ;")

    cor.append("\\begin{multicols}{2}")

    for i in range(5):
        cor += factoriseTex(melange[i])[1]

    cor.append("\\end{multicols}")

    # ## Question 2
    exo.append(u'\\item En déduire le PGCD et le PPCM des nombres ' + 
            decimaux(listenombres[1]) + " et " + decimaux(listenombres[2]) + 
            ".")
    cor.append(u'\\item En déduire le PGCD et le PPCM des nombres ' + 
            decimaux(listenombres[1]) + " et " + decimaux(listenombres[2]) + 
            ".\\par")

    cor.append(u"D'après la question 1), on sait que les nombres " + 
            decimaux(listenombres[1]) + " et " + decimaux(listenombres[2]) + 
            " ont comme facteurs premiers communs : ")

    for j in range(len(facteurs)):
        if j == 0:
            temp = "$"
        if j != len(facteurs) - 1:
            temp += decimaux(facteurs[j]) + " , "
        else:
            temp += decimaux(facteurs[j]) + "$.\\par"
    cor.append(temp)

    cor.append(u"On en déduit que le PGCD des nombres " + 
            decimaux(listenombres[1]) + " et " + decimaux(listenombres[2]) + 
            " est : ")
    temp = "$"
    if len(facteurs) > 1:
        for j in range(len(facteurs)):
            if j != len(facteurs) - 1:
                temp += decimaux(facteurs[j]) + " \\times "
            else:
                temp += decimaux(facteurs[j]) + " = "

    temp += decimaux(fauxpgcd * pgcdcompl) + ".$\\par"
    cor.append(temp)

    vraippcm = (listenombres[1] * listenombres[2]) / (fauxpgcd * pgcdcompl)

    if (listenombres[1] % listenombres[2] == 0):
        cor.append(decimaux(listenombres[1]) + u" est un multiple de " + 
              decimaux(listenombres[2]) + u", donc leur PPCM est directement "
                 + decimaux(listenombres[1]) + ".")
    elif (listenombres[2] % listenombres[1] == 0):
        cor.append(decimaux(listenombres[2]) + u" est un multiple de " + 
              decimaux(listenombres[1]) + u", donc leur PPCM est directement " + 
              decimaux(listenombres[2]) + ".")
    else:
        cor.append(u"Il existe plusieurs méthodes pour calculer le PPCM de " + 
              decimaux(listenombres[1]) + " et de " + decimaux(listenombres[2]) + 
              ".\\par")
        cor.append(u"En voici deux :")
        cor.append("\\begin{enumerate}")

        cor.append(u"\\item On peut simplement utiliser la formule :")
        cor.append(u"$a \\times b = PGCD(a;~b) \\times PPCM(a;~b)$.\\par")
        cor.append(u"Donc : $PPCM(" + decimaux(listenombres[1]) + ";~" + 
          decimaux(listenombres[2]) + ") = " + "\\dfrac{" + 
          decimaux(listenombres[1]) + "\\times" + decimaux(listenombres[2]) + "}{"
          + decimaux(fauxpgcd * pgcdcompl) + "} = " + decimaux(vraippcm) + 
          ".$")

        cor.append(u"\\item On peut aussi multiplier un nombre par les \"facteurs "
          + u"complémentaires\" de l'autre.\n" + u"Ces \"facteurs " + 
          u"complémentaires\" sont les facteurs qui complètent le PGCD pour " + 
          u"former le nombre.\\par")

        temp = u"Comme $PGCD(" + decimaux(listenombres[1]) + ";~" + \
              decimaux(listenombres[2]) + ") = " + decimaux(fauxpgcd * pgcdcompl)

        if len(facteurs) > 1:
            temp += " = "
            for j in range(len(facteurs)):
                if j != len(facteurs) - 1:
                    temp += decimaux(facteurs[j]) + " \\times "
                else:
                    temp += decimaux(facteurs[j])

        factornb1 = factoriseTex(listenombres[1])[0]

        if len(factornb1) > 1:
            textcompl = u"$, alors les \"facteurs complémentaires\" de $"
        else:
            textcompl = u"$, alors le \"facteur complémentaire\" de $"

        temp += textcompl + decimaux(listenombres[1]) + " = "

        for j in range(len(factornb1)):
            if j != len(factornb1) - 1:
                temp += decimaux(factornb1[j]) + " \\times "
            else:
                temp += decimaux(factornb1[j])

        factcompl = factoriseTex(listenombres[1] / (fauxpgcd * pgcdcompl))[0]

        if len(factcompl) == 1:
            temp += u"$ est : "
        else:
            temp += u"$ sont : "
        for j in range(len(factcompl)):
            if j != len(factcompl) - 1:
                temp += decimaux(factcompl[j]) + " , "
            else:
                temp += decimaux(factcompl[j]) + ".\n"
        temp += u"On en déduit que $PPCM(" + decimaux(listenombres[1]) + ";~" + \
              decimaux(listenombres[2]) + ") = " + decimaux(listenombres[2]) + \
              " \\times "

        for j in range(len(factcompl)):
            if j != len(factcompl) - 1:
                temp += decimaux(factcompl[j]) + " \\times "
            else:
                temp += decimaux(factcompl[j]) + " = "
        temp += decimaux(vraippcm) + ".$"
        cor.append(temp)
        cor.append("\\end{enumerate}")

    # ## Question 3

    exo.append(u"\\item Quel est le plus petit nombre par lequel il faut " + 
            u"multiplier " + decimaux(autresnombres[0]) + 
            u" pour obtenir un carré parfait ?")

    cor.append(u" \\item Pour obtenir un carré parfait, il faut que sa " + 
            u"décomposition en facteurs premiers ne contienne que des facteurs "
            + u"apparaissant un nombre pair de fois. D'après la question 1, " + 
            u"la décomposition en facteurs premiers de "
            + decimaux(autresnombres[0]))

    decompautre = factoriseTex(autresnombres[0])[1]

    if len(decompautre) == 1:
        cor.append(u" est lui-même, car c'est un nombre premier.")
    else:
        cor.append(" est : \\par\n$" + decimaux(autresnombres[0]) + " = " + 
              decompautre[-2][5:-2] + ".$\\par")

    cor.append(u"Il faut donc encore multiplier ce nombre par ")

    carre = carrerise(autresnombres[0])
    factsup = factoriseTex(carre)[0]

    if len(factsup) == 1:
        cor.append(" le facteur ")
    else:
        cor.append(" les facteurs ")

    for j in range(len(factsup)):
        if (j != len(factsup) - 1) and (j != len(factsup) - 2):
            cor.append(decimaux(factsup[j]) + " , ")
        elif (j == len(factsup) - 2):
            cor.append(decimaux(factsup[j]) + " et ")
        else:
            cor.append(decimaux(factsup[j]) + ".\\par")

    cor.append(u"Le nombre cherché est par conséquent " + decimaux(carre) + 
            u" et le carré parfait obtenu est " + decimaux(carre * 
                autresnombres[0]) + ".")

    # ## Question 4
    exo.append(u"\\item Rendre la fraction $\\dfrac{" + decimaux(listenombres[1])
            + "}{" + decimaux(listenombres[2]) + u"}$ irréductible.")

    cor.append(u"\\item Le moyen le plus rapide de simplifier cette fraction est"
            + u"de diviser le numérateur et le dénominateur par leur PGCD." + 
            u" D'après la question 2),  PGCD(" + decimaux(listenombres[1]) + ";~"
            + decimaux(listenombres[2]) + ") = "
            + decimaux(fauxpgcd * pgcdcompl) + ", donc on obtient :\\par")
    cor.append(u"$\dfrac{" + decimaux(listenombres[1]) + "{\\scriptstyle \\div " + 
            decimaux(fauxpgcd * pgcdcompl) + "}}{" + decimaux(listenombres[2]) + 
            "{\\scriptstyle \\div " + decimaux(fauxpgcd * pgcdcompl) + 
            "}} = \dfrac{" + decimaux(listenombres[1] / (fauxpgcd * pgcdcompl)) + 
            "}{" + decimaux(listenombres[2] / (fauxpgcd * pgcdcompl)) + "}.$")

    # ## Question 5

    num = [randint(6, 50), randint(6, 50)]
    exo.append(u"\\item Calculer $\\dfrac{" + decimaux(num[0]) + "}{" + 
            decimaux(listenombres[1]) + "} + \\dfrac{" + decimaux(num[1]) + "}{" + 
            decimaux(listenombres[2]) + "}$.")

    mult1 = vraippcm / listenombres[1]
    mult2 = vraippcm / listenombres[2]

    num1 = mult1 * num[0]
    num2 = mult2 * num[1]

    simplfin = pgcd(num1 + num2, vraippcm)

    if simplfin != 1:
        simpl = "{\\scriptstyle \\div " + decimaux(simplfin) + "}"
        result = " = \\dfrac{" + decimaux((num1 + num2) / simplfin) + "}{" + \
              decimaux((vraippcm) / simplfin) + "}"
    else:
        simpl = ""
        result = ""

    cor.append(u"\\item Il faut mettre les fractions au même dénominateur. Grâce"
            + u"à la question 2), nous avons déjà un dénominateur commun : " + 
            u"le PPCM des nombres " + decimaux(listenombres[1]) + " et " + 
            decimaux(listenombres[2]) + u", qui est par définition le plus petit"
            + u"multiple commun de ces deux nombres.\\par")
    cor.append(u"$\\dfrac{" + decimaux(num[0]) + "{\\scriptstyle \\times " + 
            decimaux(mult1) + "}}{" + decimaux(listenombres[1]) + 
            "{\\scriptstyle \\times " + decimaux(mult1) + "}} + \\dfrac{" + 
            decimaux(num[1]) + "{\\scriptstyle \\times " + decimaux(mult2) + "}}{"
            + decimaux(listenombres[2]) + "{\\scriptstyle \\times " + 
            decimaux(mult2) + "}} = \\dfrac{" + decimaux(num1) + "}{" + 
            decimaux(vraippcm) + "} + \\dfrac{" + decimaux(num2) + "}{" + 
            decimaux(vraippcm) + "} = \\dfrac{" + decimaux(num1 + num2) + simpl + 
            "}{" + decimaux(vraippcm) + simpl + "}" + result + ".$")

    exo.append("\\end{enumerate}")
    cor.append("\\end{enumerate}")

    return (exo, cor)