How to use the pyromaths.classes.Fractions.Fraction function in pyromaths

To help you get started, we’ve selected a few pyromaths examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Pyromaths / pyromaths / src / pyromaths / ex / lycee / Derivation.py View on Github external
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]):
github Pyromaths / pyromaths / src / pyromaths / classes / SquareRoot.py View on Github external
def print_coef(coef):
            """Gère le format du coef
            """
            if isinstance(coef, (float, int)):
                if coef > 0: return "+" + decimaux(coef)
                else: return decimaux(coef)
            if isinstance(coef, classes.Fractions.Fraction):
                if isinstance(coef.n, int) and isinstance(coef.d, int) and coef.n < 0 and coef.d > 0:
                    return "-" + str(Fraction(-coef.n, coef.d, coef.code))
                return "+" + str(coef)
            if isinstance(coef, str):
                texte = "(" + "".join(Priorites3.texify([Priorites3.splitting(coef)])) + ")"
                if texte[0] != "-": return "+" + texte
                else: return texte
        s = ""
github Pyromaths / pyromaths / src / pyromaths / outils / Priorites3.py View on Github external
s += "( " + texfrac + " )"
                else:
                    s += texfrac
            elif el[:11] == "SquareRoot(":
                p = eval(el)
                if index + 1 < len(calcul): q = calcul[index + 1]
                else: q = ""
                """ 3 cas :
                * {*,-}(2x+3) ou {*,-}(-2x)
                * (2x+3)*...
                * (2x+1)**2"""
                if (s and s[-1] in "*-" and (len(p) > 1 or p[0][0] < 0)) \
                    or (q and q == "*" and len(p) > 1) \
                    or ((len(p) > 1 or (p[0][0] != 1 and p[0][1] > 0) or \
                         p[0][0] < 0 or \
                         (p[0][0] != 1 and isinstance(p[0][0], Fraction) and p[0][0].d != 1)) and q and q == "**"):
                    s += "(" + str(p) + ")"
                elif s and s[-1] == "+" and p[0][0] < 0:
                    s = s[:-1]
                    s += str(p)
                else:
                    s += str(p)
            elif EstNombre(el):
                if index + 1 < len(calcul): q = calcul[index + 1]
                else: q = ""
                if el[0] == "(": s += "(" + decimaux(el[1:-1]) + ")"

                elif el[0] == '-' and ((s and s[-1] in "+/*-") \
                    or (q and q == "**")):
                    s += "(" + decimaux(el) + ")"

                else: s += decimaux(el)
github Pyromaths / pyromaths / src / pyromaths / ex / troisiemes / developpements.py View on Github external
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]))
github Pyromaths / pyromaths / src / pyromaths / ex / troisiemes / proba.py View on Github external
"\\rput(20,40){$\\dfrac{%s}{%s}$} \\rput(37,40){$\\dfrac{%s}{%s}$} \\rput(60,40){$\\dfrac{%s}{%s}$}" % (n1, tot, n2, tot, n3, tot),
         "\\rput(10,26){%s} \\rput(40,26){%s} \\rput(70,26){%s}" % (i1, i2, i3),
         "\\rput(0,10){$\\dfrac{%s}{%s}$} \\rput(7,10){$\\dfrac{%s}{%s}$} \\rput(20,10){$\\dfrac{%s}{%s}$}" % (n1 - 1, tot - 1, n2, tot - 1, n3, tot - 1),
         "\\rput(0,0){%s} \\rput(10,0){%s} \\rput(20,0){%s}" % (i1, i2, i3),
         "\\rput(30,10){$\\dfrac{%s}{%s}$} \\rput(37,10){$\\dfrac{%s}{%s}$} \\rput(50,10){$\\dfrac{%s}{%s}$}" % (n1, tot - 1, n2 - 1, tot - 1, n3, tot - 1),
         "\\rput(30,0){%s} \\rput(40,0){%s} \\rput(50,0){%s}" % (i1, i2, i3),
         "\\rput(60,10){$\\dfrac{%s}{%s}$} \\rput(67,10){$\\dfrac{%s}{%s}$} \\rput(80,10){$\\dfrac{%s}{%s}$}" % (n1, tot - 1, n2, tot - 1, n3 - 1, tot - 1),
         "\\rput(60,0){%s} \\rput(70,0){%s} \\rput(80,0){%s}" % (i1, i2, i3),
         "\\end{pspicture}",
         "\\vspace{0.3cm}",
         u"\\item Quelle est la probabilité que la première boule soit %s et la deuxième soit %s ?\\par" % (c3, c2),
         u"On note $(\\mathrm %s~,~\\mathrm %s)$ l'évènement: \\og{}la première boule tirée est %s et la deuxième tirée est %s\\fg{} et " % (i3,i2,c3,c2),
         u"on utilise l'arbre construit précédemment.\\par",
         "$p\\,(\\mathrm %s~,~\\mathrm %s)=%s \\times %s = %s$\\par" % \
                (i3, i2, str(Fraction(n3, tot)),
                 str(Fraction(n2, tot - 1)),
                 str(Fraction(n3 * n2, tot * (tot - 1)))),
         u"La probabilité que la première boule soit %s et la deuxième soit %s est égale à $\\dfrac{%s}{%s}$." % (c3, c2, n3 * n2, tot * (tot - 1)),
         u"\\item Quelle est la probabilité que la deuxième boule soit %s ?\\par" % c1,
         u"On note $(?~,~\\mathrm %s)$ l'évènement: \\og{}la deuxième boule tirée est %s\\fg{}. \\par" % (i1, c1),
         "$p\\,(?~,~\\mathrm %s)=p\\,(\\mathrm %s~,~\\mathrm %s)+p\\,(\\mathrm %s~,~\\mathrm %s)+p\\,(\\mathrm %s~,~\\mathrm %s)=" % (i1, i1, i1, i2, i1, i3, i1) + p41 + p42 + p43 + result4 + "$",
         "\\end{enumerate}"]
    for st in exos:
        exo.append(st)
    for st in cors:
        cor.append(st)
github Pyromaths / pyromaths / src / pyromaths / outils / Priorites3.py View on Github external
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]
github Pyromaths / pyromaths / src / pyromaths / ex / lycee / SecondDegre.py View on Github external
def id_rem(self, a, b, sgn):
        etapes = [['Polynome("%sx%s%s")' % (a, sgn, b), '**', '2']]
        if a != 1:
            etapes.append(['(', '%s' % a, '*', 'Polynome("x%sFraction(%s, %s)")' % (sgn, b, a), ')', '**', '2' ])
            frac = Fraction(b, a).simplifie()
            etapes.append(['%s' % (a ** 2), '*', 'Polynome("x%s%r")' % (sgn, frac), '**', '2'])
        return etapes
github Pyromaths / pyromaths / src / pyromaths / ex / lycee / SecondDegre.py View on Github external
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]])
github Pyromaths / pyromaths / src / pyromaths / ex / lycee / SecondDegre.py View on Github external
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)]
        exercice = [list(pol)]

        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]))
        sgn = -val[0] / abs(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.append([pol, val[1], val[2]])

        val = [sgn * valeur_alea(-9, 9), valeur_alea(-9, 9)]
        val.append(Fraction(valeur_alea(-9, 9), val[0]).simplifie())
        while isinstance(val[2], int) or val[2].d == 1:
            val = [sgn * 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.append([pol, val[1], val[2]])

        self.exercice = exercice