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)
def tex_equation3( valeurs): # renvoie l'ecriture reduite de l'equation sans denominateur texte = str( Polynome('%sx+%s' % (valeurs[4][0] + valeurs[4][2] * valeurs[3][1], valeurs[4][1] + valeurs[4][3] * valeurs[3][1]))) texte = texte + '=' + str( Polynome('%sx+%s' % (valeurs[4][4], valeurs[4][5]))) return texte
def tex_statement(self): exo = [r'\exercice'] exo.append(r'\begin{enumerate}') exo.append(_(u'\\item Déterminer le signe du polynôme $P\\,(x) = %s$') % Polynome(self.exercice[0])) exo.append(_(u'\\item Le polynôme $Q\\,(x) = %s$ admet deux racines $%s$ et $%s\\,$. Dresser son tableau de signes.') \ % (Polynome(self.exercice[1][0]), self.exercice[1][1], self.exercice[1][2])) exo.append(_(u'\\item Le polynôme $R\\,(x) = %s$ admet deux racines $%s$ et $%s\\,$. Dresser son tableau de signes.') \ % (Polynome(self.exercice[2][0]), self.exercice[2][1], self.exercice[2][2])) exo.append('\\end{enumerate}') return exo
def racines(p, lracines): """ Trouve les 2 racines manquantes d'un polynôme de degré 5 connaissant 3 des racines """ q = Polynome(p) for r in lracines: q = q // Polynome("x-%s" % r) delta = q[1][0]**2 - 4 * q[0][0] * q[2][0] d = float(eval(Priorites3.priorites(delta)[-1][0])) return (-float(q[1][0]) + sqrt(d)) / 2 / float( q[0][0]), (-float(q[1][0]) - sqrt(d)) / 2 / float(q[0][0])
def tex_equation2bis( valeurs ): # renvoie l'ecriture des quotients au meme denominateur sans les parentheses eventuelles texte = str(Polynome('%sx+%s' % (valeurs[4][0], valeurs[4][1]))) texte = texte + str( Polynome( '%sx+%s' % (valeurs[4][2] * valeurs[3][1], valeurs[4][3] * valeurs[3][1]))) texte = texte + '=' + str( Polynome('%sx+%s' % (valeurs[4][4], valeurs[4][5]))) return texte
def tex_statement(self): exo = [r'\exercice'] exo.append(_(u'Résoudre les équations :')) exo.append('\\begin{align*}') for e in self.exercice: if len(e) == 2: exo.append(Priorites3.texify([[repr(Polynome(e[0])), '*', repr(Polynome(e[1]))]])[0] + ' &= 0 & ') else: exo.append(r'\cfrac{%s}{%s} &= %s & ' % (Polynome(e[0]), Polynome(e[1]), Polynome(e[2]))) exo[-1] = exo[-1][:-3] # Suppression du dernier " &" exo.append('\\end{align*}') return exo
def tex_quotient1( a, b, c, d): # renvoie l'ecriture de la mise au meme denominateur d'un quotient if d == 1: return tex_quotient0(a, b, c) else: return '\\cfrac{(%s)_{\\times%s}}{%s_{\\times%s}}' % (str( Polynome([[a, 1], [b, 0]])), d, c, d)
def tex_statement(self): exo = [r'\exercice'] exo.append(r'\begin{enumerate}') exo.append(_(u'\\item Le polynôme $\\quad P\\,(x) = %s \\quad$ admet deux racines $%s$ et $%s\\,$. Donner sa forme factorisée.\n') \ % (Polynome(self.exercice[0][0]), self.exercice[0][1], self.exercice[0][2])) exo.append(_(u'\\item Factoriser si possible les polynômes $\quad Q\\,(x) = %s\\quad$ et $\\quad R\\,(x) = %s$.\n') % (Polynome(self.exercice[1][0]), Polynome(self.exercice[1][1]))) exo.append(r'\end{enumerate}') return exo
def tex_equation2( valeurs): # renvoie l'ecriture des quotients au meme denominateur texte = '\\cfrac{' texte += texify([[ 'Polynome([[%s, 1], [%s, 0]])' % (valeurs[4][0], valeurs[4][1]), valeurs[3][0], 'Polynome([[%s, 1], [%s, 0]])' % (valeurs[4][2], valeurs[4][3]) ]])[0] texte = texte + '}{\\cancel{%s}}=\cfrac{' % (valeurs[1][0] * valeurs[2][0]) texte += str(Polynome([[valeurs[4][4], 1], [valeurs[4][5], 0]])) texte = texte + '}{\\cancel{%s}}' % (valeurs[1][0] * valeurs[2][0]) return texte
def tex_statement(self): exo = [r'\exercice'] exo.append(_(u'Déterminer les racines des polynômes :')) exo.append('\\begin{align*}') noms = [r'P\,(x) &= ', r'Q\,(x) &= ', r'R\,(x) &= '] r = '' for i in range(3): r += noms[i] + str(Polynome(self.exercice[i], 'x')) if i < 2: r += ' & ' exo.append(r) exo.append('\\end{align*}') return exo
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
def tracefonc(f, i, A, B, xmin, xmax, ymin, ymax): """**tracefonc\ (*f*\ , *i*\ , *A*\ , *B*\ , *xmin*\ , *xmax*\ , *ymin*\ , *ymax*\ ) *A* est sur l'axe des ordonnées, *f* est le nom de la fonction Génère la 2e queston et sa réponse >>> from pyromaths.classes.Fractions import Fraction >>> affine.tracefonc('f', 1, (0,-2),(3,2),-4,4,-4,-4) [u'Tracer la droite repr\xe9sentative ($d_1$) de la fonction $f:x\\longmapsto \\ dfrac{4}{3}\\,x-2$.', 'On sait que $f(0)=-2$ et $f(-3)=\\dfrac{4}{3}\\times \\le ft( -3\\right) -2=\\dfrac{4\\times \\cancel{3}\\times -1}{\\cancel{3}\\times 1}- 2=-4-2=-6', '\\psdot [dotsize=4.5pt,dotstyle=x](0, -2)', '\\psdot [dotsize=4.5pt ,dotstyle=x](-3, -6.0)'] :rtype: list of string """ u = coefdir(A, B) if isinstance(u, int) or u.d == 1: x1 = decimaux(B[0]) else: B = (u.d, u.n + float(A[1])) if not dansrep(B, xmin, xmax, ymin, ymax): B = (-u.d, -u.n + float(A[1])) x1 = decimaux(str(B[0])) l = Priorites3.texify([Polynome([[u, 1], [A[1], 0]], "x")(B[0])]) l.extend( Priorites3.texify( Priorites3.priorites(Polynome([[u, 1], [A[1], 0]], "x")(B[0])))) l = [ u'Tracer la droite représentative ($d_' + str(i) + '$) de la fonction $' + f + ':x\\longmapsto ' + str(Polynome([[u, 1], [A[1], 0]], "x")) + '$.', 'On sait que $' + f + '(0)=' + decimaux(str(A[1])) + '$ et $' + f + '(' + x1 + ')=' + "=".join(l) + "$.", '\\psdot [dotsize=4.5pt,dotstyle=x]' + str(A), '\\psdot [dotsize=4.5pt,dotstyle=x]' + str(B), ] return l
def __init__(self): pol = [creerPolydegre2(nb_racines=2, rac_radical=True, rac_quotient=False)] pol.append(creerPolydegre2(nb_racines=1)) a, b = valeur_alea(-9, 9), valeur_alea(-9, 9) pol.append([[a ** 2, 2], [-b ** 2, 0]]) a, b = valeur_alea(-9, 9), valeur_alea(-9, 9) while a * b == -64: # sqrt{8} est trop long à décomposer en une demi-ligne a, b = valeur_alea(-9, 9), valeur_alea(-9, 9) pol.append([[a, 2], [b, 0]]) a, b = valeur_alea(-9, 9), valeur_alea(-9, 9) pol.append([[a, 2], [b, 1]]) pol.pop(randrange(1, len(pol))) pol.pop(randrange(1, len(pol))) shuffle(pol) for i in range(3): m = list(pol[i]) shuffle(m) pol[i] = m print(str(Polynome(pol[i], "x"))) self.exercice = pol
def __init__(self): val = [valeur_alea(-9, 9), valeur_alea(-9, 9) , valeur_alea(-9, 9)] pol = Polynome([[val[0], 2], [(-val[0] * (val[1] + val[2])), 1], [(val[0] * val[1] * val[2]), 0]]) while val[2] == val[1] or abs(val[0] * val[1] * val[2]) > 10 or abs(eval(pol((val[1] + val[2]) / 2.))) > 10: val = [valeur_alea(-9, 9), valeur_alea(-9, 9) , valeur_alea(-9, 9)] pol = Polynome([[val[0], 2], [(-val[0] * (val[1] + val[2])), 1], [(val[0] * val[1] * val[2]), 0]]) val = [[val[0], 2], [(-val[0] * (val[1] + val[2])), 1], [(val[0] * val[1] * val[2]), 0]] shuffle(val) lp = [Polynome(val)] val = [[valeur_alea(-9, 9), 2 - dummy] for dummy in range(3)] val[1][0] = valeur_alea(-9, 9) * val[0][0] pol = Polynome(val) while val[1][0] ** 2 - 4 * val[0][0] * val[2][0] >= 0 or abs(eval(pol(-val[1][0] / 2. / val[0][0]))) > 10: val = [[valeur_alea(-9, 9), 2 - dummy] for dummy in range(3)] val[1][0] = valeur_alea(-9, 9) * val[0][0] pol = Polynome(val) shuffle(val) pol = Polynome(val) lp.append(pol) shuffle(lp) self.exercice = lp
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")
def tex_statement(self): exo = [r'\exercice'] exo.append(_(u'Résoudre l\'inéquation : $\qquad \\cfrac{%s}{%s} %s 0$') % (Polynome(self.exercice[0]), Polynome(self.exercice[1]), self.exercice[2])) return exo
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")
def __add__(self, *others): """*object*\ .\ **__add__**\ (*other*) ``p.__add__(q)`` est équivalent à ``p + q`` calcule la somme de 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", "r")+Fraction(2, 10)' >>> Fraction(2,20) + Fraction(2,10) 'Fraction(2, 20)+Fraction("2*2", "10*2", "r")' >>> Fraction(5,10) + Fraction(2,10) Fraction(7, 10) >>> Fraction(5,7) + Fraction(2,10) 'Fraction("5*10", "7*10", "r")+Fraction("2*7", "10*7", "r")' :param: other :type: Fraction ou string :rtype: Fraction ou string **TODO :** Attention, 1+3/4 donne 1*4/1*4 + 3/4 à la place de 4/4+3/4. À corriger """ from pyromaths.classes.PolynomesCollege import Polynome lother, lden, traiter = [], [], False if self.code: traiter = True details, var = '', '' for other in others: if other == 0: pass elif isinstance(other, Polynome): var = other.var if details != 0 : details = min(details, other.details) else: details = other.details lother.append(other) elif isinstance(other, (int, float)): lother.append(Fraction(other)) lden.append(1) elif isinstance(other, Fraction): lother.append(other) if other.code: traiter = True try: lden.append(eval(other.d)) except TypeError: lden.append(other.d) else: raise ValueError(u'Format incorrect : %s' % (other)) if var: self = Polynome([[self, 0]], var, details) for i in range(len(lother)): if not isinstance(lother[i], Polynome): lother[i] = Polynome([[lother[i], 0]], var, details) return Polynome.__add__(self, *lother) 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 if not lother: return self # On a ajouté 0 leppcm = ppcm(self.d, *lden) if self.d == leppcm: # Vérifions si toutes les fractions ont le même dénominateur d = Counter(lden) if d[leppcm] == len(lden): try: num = eval(self.n) except TypeError: num = self.n for other in lother: try: num += eval(other.n) except TypeError: num += other.n return Fraction(num, leppcm) if self.n: lfrac = [repr(self.choix_denominateur(leppcm))] else: lfrac = [] for other in lother: lfrac.append(repr(other.choix_denominateur(leppcm))) if lfrac: return "+".join(lfrac) else: return "0"
def tex_answer(self): exo = [r'\exercice*'] exo.append(_(u'Déterminer les racines des polynômes :\\par')) noms = [r'P\,(x) &= ', r'Q\,(x) &= ', r'R\,(x) &= '] r = '' question = [[], [], []] for i in range(3): p = [] m = Polynome(list(self.exercice[i])).ordonne() if factoriser('%r' % Polynome(m)): p = [factoriser('%r' % Polynome(m))] while factoriser(p[-1]): p.append(factoriser(p[-1])) if p and eval(Priorites3.splitting(p[-1])[0]).degre() > 0: tmp = Priorites3.texify([Priorites3.splitting(p[j]) for j in range(len(p))]) question[i].append('{$\\! \\begin{aligned}') question[i].append(noms[i] + str(Polynome(m, 'x')) + r'\\') question[i].append('\\\\\n'.join(['&=%s' % (tmp[j]) for j in range(len(tmp))])) question[i].append(r'\end{aligned}$}\par') lp = Priorites3.splitting(p[-1]) racines = [] for e in lp: if e[:9] == 'Polynome(': e = eval(e) if len(e) == 2: racines.append(str(Fraction(-e[1][0], e[0][0]).simplifie())) else: racines.append('0') if len(racines) > 1: question[i].append(_(u'\\underline{Les racines de $%s$ sont }\\fbox{$%s$}') % (noms[i].rstrip(r' &= '), '$}\\underline{ et }\\fbox{$'.join(racines))) elif len(racines) == 1: question[i].append(_(u'\\underline{L\'unique racine de $%s$ est }\\fbox{$%s$}') % (noms[i].rstrip(r' &= '), racines[0])) elif len(m) == 2 and m[0][1] == 2 and m[1][1] == 0 and m[0][0] * m[1][0] > 0: question[i].append('$' + noms[i] + str(Polynome(m, 'x')) + r'$\par') question[i][-1] = question[i][-1].replace('&', '') if m[1][0] > 0: question[i].append('$' + noms[i][:7] + ' \\geqslant %r$' % m[1][0]) else: question[i].append('$' + noms[i][:7] + ' \\leqslant %r$' % m[1][0]) question[i].append(_(u'car un carré est toujours positif.\\par\n\\underline{$%s$ n\'a donc pas de racine.}') % (noms[i].rstrip(r' &= '))) else: question[i].append('$' + noms[i] + str(Polynome(m, 'x')) + r'\quad$') question[i][-1] = question[i][-1].replace('&', '') question[i].append(_(u'On calcule le discriminant de $%s$ avec $a=%s$, $b=%s$ et $c=%s$ :\\par\\medskip') % (noms[i].rstrip(r' &= '), m[0][0], m[1][0], m[2][0])) question[i].append(r'\begin{tabularx}{\linewidth}[t]{XXX}') question[i].append(r'{$\! \begin{aligned}') if m[1][0]>0: sol = [[str(m[1][0]), '**', '2', '-', '4', '*', str(m[0][0]), '*', str(m[2][0])]] sol.extend(Priorites3.priorites('%s**2-4*%s*%s' % (m[1][0], m[0][0], m[2][0]))) else: sol = [['(', str(m[1][0]), ')', '**', '2', '-', '4', '*', str(m[0][0]), '*', str(m[2][0])]] sol.extend(Priorites3.priorites('(%s)**2-4*%s*%s' % (m[1][0], m[0][0], m[2][0]))) solTeX = Priorites3.texify(sol) for s in solTeX: question[i].append(u'\\Delta &= %s\\\\' % s) question[i].append(r'\end{aligned}$}') question[i].append(r'&') question[i].append(r'{$\! \begin{aligned}') delta = sol[-1][0] print(sol) sol = [['Fraction(SquareRoot([[%s, None], [-1, %s]]),\'2*%s\')' % (-m[1][0], delta, m[0][0])]] sol.extend(Priorites3.priorites(sol[0][0])) sol = Priorites3.texify(sol) for s in sol: question[i].append(u'x_1 &= %s\\\\' % s) racines = [sol[-1]] question[i].append(r'\end{aligned}$}') question[i].append(r'&') question[i].append(r'{$\! \begin{aligned}') sol = [['Fraction(SquareRoot([[%s, None], [1, %s]]),\'2*%s\')' % (-m[1][0], delta, m[0][0])]] sol.extend(Priorites3.priorites(sol[0][0])) sol = Priorites3.texify(sol) for s in sol: question[i].append(u'x_2 &= %s\\\\' % s) racines.append(sol[-1]) question[i].append(r'\end{aligned}$}') question[i].append(r'\end{tabularx}\par') question[i].append(_(u'\\underline{Les racines de $%s$ sont }\\fbox{$%s$}') % (noms[i].rstrip(r' &= '), _('$}\\underline{ et }\\fbox{$').join(racines))) if i == 1: question.append(question[1]) if len(question) == 4: question.pop(1) if question[0][0][-6:] == r'\quad$': question[1].insert(0, r'\par\medskip\begin{tabularx}{\linewidth}[t]{XX}') question[2].insert(0, r'&') question[2].append(r'\end{tabularx}\par\medskip') else: question[0].insert(0, r'\begin{tabularx}{\linewidth}[t]{XX}') question[1].insert(0, r'&') question[1].append(r'\end{tabularx}\par\medskip') for i in range(3): exo.extend(question[i]) return exo
def tex_statement(self): exo = [r'\exercice'] exo.append(r'\begin{enumerate}') exo.append(_(u'\\item On donne le polynôme $\\quad P\\,(x) = %s\\quad$ où $m$ est un réel.\\par') % self.exercice[0][0]) # TODO: Affichage des paramètres et parenthèses exo.append(_(u'Quelles sont les valeurs de $m$ pour lesquelles $P$ %s ?\n') % [_('a une seule racine'), _('n\'a pas de racine'), _('a deux racines distinctes')][self.exercice[0][1]]) # exo.append(u'\\par Solution : Polynôme en m : $%s$\\par\n' % (Polynome([[a ** 2, 2], [2 * a * b - 4 * c, 1], [b ** 2 - 4 * d, 0]], "m")) # exo.append( u'Solution : discriminant $\\Delta_m = %s$\\par\n' % (16 * (a ** 2 * d - a * b * c + c ** 2)) exo.append(_(u'\\item Soit $a$ un réel différent de $%s$. On donne $Q\\,(x) = %s$.\\par\n') % (self.exercice[1][1], Polynome(self.exercice[1][0]))) exo.append(_(u'Déterminer $a$ pour que $%s$ soit une racine de $Q$.\n') % self.exercice[1][2]) exo.append(r'\end{enumerate}') return exo
def effectue_calcul(calcul): """**effectue_calcul**\ (*calcul*) Effectue une étape du calcul en respectant les priorités :param calcul: le calcul à traiter :type calcul: list >>> from pyromaths.outils import Priorites3 >>> Priorites3.effectue_calcul(['-5', '-', '(', '(-6)', '-', '1', '+', '(-3)', ')', '*', '(-1)']) ['-5', '-', '(', '-7', '-', '3', ')', '*', '(-1)'] >>> Priorites3.effectue_calcul(['-5', '-', '(', '-7', '-', '3', ')', '*', '(-1)']) ['-5', '-', '-10', '*', '(-1)'] >>> Priorites3.effectue_calcul(['-5', '-', '-10', '*', '(-1)']) ['-5', '-', '10'] >>> Priorites3.effectue_calcul(['-5', '-', '10']) ['-15'] >>> Priorites3.effectue_calcul(['-', 'Polynome("x-1")', '*', '2']) ['-', '(', 'Polynome([[2, 1]], "x", 0)', '+', 'Polynome([[-2, 0]], "x", 0)', ')'] >>> Priorites3.effectue_calcul(['4', '*', 'Polynome("x+1")', '**', '2']) ['4', '*', '(', 'Polynome([[1, 1]], "x", 0)', '**', '2', '+', '2', '*', 'Polynome([[1, 1]], "x", 0)', '*', 'Polynome([[1, 0]], "x", 0)', '+', 'Polynome([[1, 0]], "x", 0)', '**', '2', ')'] :rtype: list """ from pyromaths.classes.PolynomesCollege import Polynome from pyromaths.classes.Fractions import Fraction from pyromaths.classes.SquareRoot import SquareRoot serie = (recherche_parentheses, recherche_puissance, recherche_produit, recherche_neg, recherche_somme) result, post, break_somme = [], "", False for recherche in serie: if break_somme and recherche == recherche_somme: break if calcul: test = recherche(calcul) else: test = None while test: pre = calcul[:test[0]] calc = calcul[test[0]:test[1]] post = calcul[test[1]:] # On essaie d'utiliser les priorités sur la première partie du # calcul pour raccourcir la résolution de l'expression if test != recherche_neg and pre: # Si on simplifie les écritures, on n'essaie pas les sommes tmp = effectue_calcul(pre) if tmp and result and result[-1] not in "+-**/(" and tmp[0][0]\ not in "+-*/)": # un signe + si l'expression en a besoin result.append("+") # On ajoute le résultat ou l'expression if tmp: result.extend(tmp) else: result.extend(pre) else: result.extend(pre) if recherche == recherche_parentheses: # On supprime les parenthèses autour de l'expression calc = calc[1:-1] # On réduit directement les calculs numériques dans une # expression littérale "Effectue les calculs entre parenthèses et remet les parenthèses si l'expression est de longueur supérieure à 1" sol = effectue_calcul(calc) if len(sol) > 1: sol.insert(0, "(") sol.append(")") elif sol and isinstance(eval(sol[0]), (int, float, Fraction)) and post and post[0] == "*" and \ _('Polynome(') in post[1] and len(eval(post[1])) == 1 and eval(post[1])[0][0] == 1: # Sans doute une factorisation de sommes de polynômes sol = [repr(eval(sol[0]) * eval(post[1]))] post = post[2:] # Suppression des parenthèses autour de ((9.0-80.0)*Polynome("x")) devenu (Polynome("-71.0x")) if post and result and post[0] == ")" and result[-1] == "(" : result, post = result[:-1], post[1:] else: if recherche == recherche_somme: # Permet les cas 1 + Fraction(1, 2) + 1 # ou 3 + Polynome("5x") + 4 frac, poly, nombres = False, False, [] for i in range(0, len(calc), 2): nombres.append(eval(calc[i])) if isinstance(nombres[-1], Fraction): frac = True elif isinstance(nombres[-1], Polynome): poly, var, details = True, nombres[-1].var, nombres[-1].details if poly: nombres = [(Polynome([[i, 0]], var, details) , i)[isinstance(i, Polynome)] for i in nombres] elif frac: nombres = [(Fraction(i, 1), i)[isinstance(i, Fraction)] for i in nombres] if poly: classe = Polynome elif frac: classe = Fraction if poly or frac: if calc[1] == '+': operation = classe.__add__ else: operation = classe.__sub__ if isinstance(nombres[0], (int, float)): sol = operation(classe(nombres[0]), *nombres[1:]) else: sol = operation(nombres[0], *nombres[1:]) else: sol = eval("".join(calc)) elif recherche == recherche_produit and calc[1] == "*": frac, poly, nombres = False, False, [] for i in range(0, len(calc), 2): nombres.append(eval(calc[i])) if isinstance(nombres[-1], Fraction): frac = True elif isinstance(nombres[-1], Polynome): poly, var, details = True, nombres[-1].var, nombres[-1].details if poly: nombres = [(Polynome([[i, 0]], var, details) , i)[isinstance(i, Polynome)] for i in nombres] elif frac: nombres = [(Fraction(i, 1), i)[isinstance(i, Fraction)] for i in nombres] if poly: classe = Polynome elif frac: classe = Fraction if poly or frac: if isinstance(nombres[0], (int, float)): sol = classe.__mul__(classe(nombres[0]), *nombres[1:]) else: sol = classe.__mul__(nombres[0], *nombres[1:]) else: sol = eval("".join(calc)) elif recherche == recherche_puissance: sol = eval('(' + calc[0] + ')**' + calc[2]) else: sol = eval("".join(calc)) if isinstance(sol, basestring): sol = splitting(sol) elif isinstance(sol, (int, float)): sol = [str(sol)] elif isinstance(sol, (Polynome, Fraction, SquareRoot)): sol = [repr(sol)] else : raise ValueError(_(u"Le résultat %s a un format inattendu") % sol) if recherche == recherche_neg and (pre or result): # Ajoute le "+" ou sépare le "-": # "1-(-9)" => "1 + 9" et "1+(-9)" => "1 - 9" if sol[0][0] == "-": sol = ["-", sol[0][1:]] else: sol = ["+", sol[0]] #=================================================================== # if recherche == recherche_produit and len(sol) > 1: # # Ajoute les parenthèses si produit précédé d'un "-" ou "*" # # ou suivi d'un "*" #=================================================================== if len(sol) > 1 and sol[0] != "(" and sol[-1] != ")": # Ajoute les parenthèses si le résultat est précédé d'un "-" ou "*" # ou suivi d'un "*" if (result and result[-1] in "*-") or (pre and pre[-1] in "*-") or (post and post[0] == "*"): sol.insert(0, "(") sol.append(")") # Si @sol est négatif et @result se termine par un "+", on l'enlève if result and result[-1] == "+" and sol and sol[0][0] == "-": result[-1] = "-" sol[0] = sol[0].lstrip("-") result.extend(sol) calcul = post if calcul: test = recherche(calcul) else: test = None if post and recherche == recherche_neg: break_somme = True result.extend(post) if not result: result = calcul return result
def __sub__(self, *others): """*object*\ .\ **__sub__**\ (*other*) ``p.__sub__(q)`` est équivalent à ``p - q`` calcule la différence de deux fractions. *other* peut être une chaîne représentant une fraction, un entier ou un réel. Pour plus de détails, voir :py:func:`__add__`""" from pyromaths.classes.PolynomesCollege import Polynome lother, lden, traiter = [], [], False if self.code: traiter = True details, var = True, '' for other in others: if other == 0: pass elif isinstance(other, Polynome): var = other.var if details != 0: details = min(details, other.details) else: details = other.details lother.append(other) elif isinstance(other, (int, float)): lother.append(Fraction(other)) lden.append(1) elif isinstance(other, Fraction): lother.append(other) if other.code: traiter = True try: lden.append(eval(other.d)) except TypeError: lden.append(other.d) else: raise ValueError(u'Format incorrect : %s' % (other)) if var: self = Polynome([[self, 0]], var, details) for i in range(len(lother)): if not isinstance(lother[i], Polynome): lother[i] = Polynome([[lother[i], 0]], var, details) return Polynome.__sub__(self, *lother) 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 if not lother: return self # On a ajouté 0 leppcm = ppcm(self.d, *lden) if self.d == leppcm: # Vérifions si toutes les fractions ont le même dénominateur d = Counter(lden) if d[leppcm] == len(lden): try: num = eval(self.n) except TypeError: num = self.n for other in lother: try: num += -eval(other.n) except TypeError: num += -other.n return Fraction(num, leppcm) if self.n: lfrac = [repr(self.choix_denominateur(leppcm))] else: lfrac = [] for other in lother: if lfrac: lfrac.append(repr(other.choix_denominateur(leppcm))) else: lfrac.append(repr(-other.choix_denominateur(leppcm))) # On effectue Fraction(0,3)-Fraction(2,3), il faut donc prendre l'opposé de Fraction(2,3), puisque Fraction(0,3) a été supprimée if lfrac: return "-".join(lfrac) else: return "0"
def tex_quotient0(a, b, c): # renvoie l'ecriture d'un quotient de l'enonce return '\\cfrac{%s}{%s}' % (str(Polynome('%sx+%s' % (a, b))), c)
def __sub__(self, *others): """*object*\ .\ **__sub__**\ (*other*) ``p.__sub__(q)`` est équivalent à ``p - q`` calcule la différence de deux fractions. *other* peut être une chaîne représentant une fraction, un entier ou un réel. Pour plus de détails, voir :py:func:`__add__`""" from pyromaths.classes.PolynomesCollege import Polynome lother, lden, traiter = [], [], False if self.code: traiter = True details, var = True, '' for other in others: if other == 0: pass elif isinstance(other, Polynome): var = other.var if details != 0 : details = min(details, other.details) else: details = other.details lother.append(other) elif isinstance(other, (int, float)): lother.append(Fraction(other)) lden.append(1) elif isinstance(other, Fraction): lother.append(other) if other.code: traiter = True try: lden.append(eval(other.d)) except TypeError: lden.append(other.d) else: raise ValueError(u'Format incorrect : %s' % (other)) if var: self = Polynome([[self, 0]], var, details) for i in range(len(lother)): if not isinstance(lother[i], Polynome): lother[i] = Polynome([[lother[i], 0]], var, details) return Polynome.__sub__(self, *lother) 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 if not lother: return self # On a ajouté 0 leppcm = ppcm(self.d, *lden) if self.d == leppcm: # Vérifions si toutes les fractions ont le même dénominateur d = Counter(lden) if d[leppcm] == len(lden): try: num = eval(self.n) except TypeError: num = self.n for other in lother: try: num += -eval(other.n) except TypeError: num += -other.n return Fraction(num, leppcm) if self.n: lfrac = [repr(self.choix_denominateur(leppcm))] else: lfrac = [] for other in lother: if lfrac: lfrac.append(repr(other.choix_denominateur(leppcm))) else: lfrac.append(repr(-other.choix_denominateur(leppcm))) # On effectue Fraction(0,3)-Fraction(2,3), il faut donc prendre l'opposé de Fraction(2,3), puisque Fraction(0,3) a été supprimée if lfrac: return "-".join(lfrac) else: return "0"
def __add__(self, *others): """*object*\ .\ **__add__**\ (*other*) ``p.__add__(q)`` est équivalent à ``p + q`` calcule la somme de 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", "r")+Fraction(2, 10) >>> Fraction(2,20) + Fraction(2,10) Fraction(2, 20)+Fraction("2*2", "10*2", "r") >>> repr(Fraction(5,10) + Fraction(2,10)) Fraction(7, 10) >>> Fraction(5,7) + Fraction(2,10) Fraction("5*10", "7*10", "r")+Fraction("2*7", "10*7", "r") :param: other :type: Fraction ou string :rtype: Fraction ou string **TODO :** Attention, 1+3/4 donne 1*4/1*4 + 3/4 à la place de 4/4+3/4. À corriger """ from pyromaths.classes.PolynomesCollege import Polynome lother, lden, traiter = [], [], False if self.code: traiter = True details, var = '', '' for other in others: if other == 0: pass elif isinstance(other, Polynome): var = other.var if details != 0: details = min(details, other.details) else: details = other.details lother.append(other) elif isinstance(other, (int, float)): lother.append(Fraction(other)) lden.append(1) elif isinstance(other, Fraction): lother.append(other) if other.code: traiter = True try: lden.append(eval(other.d)) except TypeError: lden.append(other.d) else: raise ValueError(u'Format incorrect : %s' % (other)) if var: self = Polynome([[self, 0]], var, details) for i in range(len(lother)): if not isinstance(lother[i], Polynome): lother[i] = Polynome([[lother[i], 0]], var, details) return Polynome.__add__(self, *lother) 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 if not lother: return self # On a ajouté 0 leppcm = ppcm(self.d, *lden) if self.d == leppcm: # Vérifions si toutes les fractions ont le même dénominateur d = Counter(lden) if d[leppcm] == len(lden): try: num = eval(self.n) except TypeError: num = self.n for other in lother: try: num += eval(other.n) except TypeError: num += other.n return Fraction(num, leppcm) if self.n: lfrac = [repr(self.choix_denominateur(leppcm))] else: lfrac = [] for other in lother: lfrac.append(repr(other.choix_denominateur(leppcm))) if lfrac: return "+".join(lfrac) else: return "0"
def exprfonc(f, i, A, B): # Génère la 3e question. # A est sur l'axe des ordonnées, f est le nom de la fonction u = coefdir(A, B) if isinstance(u, int): u = Fraction(u, 1) Polynome([[u, 1], [A[1], 0]], "x")(B[0]) #=========================================================================== # if A[1] >= 0: # b = '+' + decimaux(str(A[1])) # else: # b = decimaux(str(A[1])) # if u.d == 1: # coef = decimaux(str(u.n)) # if u.n == -1: # coef = '-' # utilisé dans l'expression de la fonction # if u.n == 1: # coef = '' # coefres = decimaux(str(u.n)) # résultat utilisé pour a # else: # if u.n > 0: # coef = '\\dfrac{' + decimaux(str(u.n)) + '}{' + decimaux(str(u.d)) + '}' # else: # coef = '-\\dfrac{' + decimaux(str(abs(u.n))) + '}{' + decimaux(str(u.d)) + '}' # coefres = coef #=========================================================================== if A[1] - B[1] > 0: deltay = '+' + decimaux(str(A[1] - B[1])) else: deltay = decimaux(str(A[1] - B[1])) if A[0] - B[0] > 0: deltax = '+' + decimaux(str(A[0] - B[0])) else: deltax = decimaux(str(A[0] - B[0])) if float(B[0]) < 0: mid11 = float(B[0]) - 0.75 mid12 = float((B[1] + A[1])) / 2 # milieu de la flèche verticale else: mid11 = float(B[0]) + 0.75 mid12 = float((B[1] + A[1])) / 2 if float(B[0]) * float(u.d / u.n) > 0: mid21 = float((A[0] + B[0])) / 2 mid22 = A[1] - 0.6 # milieu de la flèche horizontale else: mid21 = float((A[0] + B[0])) / 2 mid22 = A[1] + 0.5 if mid12 < 0 and mid12 > -0.8: mid12 = -1 if mid12 >= 0 and mid12 < 0.5: mid12 = 0.5 if mid11 < 0 and mid11 > -0.8: mid11 = -1 if mid11 >= 0 and mid11 < 0.5: mid11 = 0.5 if mid21 < 0 and mid21 > -0.8: mid21 = -1 if mid21 >= 0 and mid21 < 0.5: mid21 = 0.5 if mid22 < 0 and mid22 > -0.8: mid22 = -1 if mid22 >= 0 and mid22 < 0.5: mid22 = 0.5 mid1 = (mid11, mid12) mid2 = (mid21, mid22) l = [ u'Déterminer l\'expression de la fonction $' + f + u'$ représentée ci-contre par la droite ($d_' + str(i) + '$).', u'On lit l\'ordonnée à l\'origine et le coefficient de la fonction affine sur le graphique.\\\ ', '$' + f + '(x)=a\\,x+b$ ' + 'avec $b=' + decimaux(str(A[1])) + '$ et $a=' + '\\dfrac{' + deltay + '}{' + deltax + '}=' + str(u) + '$.\\\ ', 'L\'expression de la fonction $' + f + '$ est $' + f + '(x)=' + str(Polynome([[u, 1], [A[1], 0]], "x")) + '$.', doublefleche(B, (B[0], A[1])), doublefleche((B[0], A[1]), A), '\\rput' + str(mid1) + '{(' + deltay + ')}', '\\rput' + str(mid2) + '{(' + deltax + ')}' ] return l