Exemple #1
0
def qSignificantFigures_template():
    '''Significant figures. e.g. Evaluate cuberoot(651/3) to 5 sig fig.'''
    sig_fig = randint(2,5)
    root_val = randint(2,5)
    numerator = randint(1,1000)
    denom = randint(1,1000)
    val = 'root%s(%s/(%s*pi))' % (root_val, numerator, denom)
    question = 'Evaluate ' +  tostring(am.parse(val)) + ' to %s' % (sig_fig)
    question += ' Significant Figures.'

    steps = []
    inside_root = (numerator/(denom*pi)).evalf() 
    val = root(inside_root, root_val)
    steps.append('This has to be done with a calculator.')
    steps.append('Do the inside calucation first: ' + 
                 tostring(am.parse('%s/(%s*pi)'%(numerator,denom))) + tostring(am.parse('*'))
                 + str(am.parse('pi')))
    steps.append('This should give ' + tostring(am.parse(str(inside_root))))
    steps.append('Then you need to square root the answer.')
    steps.append('Use either [1/y] key or similar on calculator and press ' 
                 + str(root_val))
    steps.append('Please refer to your calculator manual if in doubt.')
    steps.append('Then look for %s significant figures.' % sig_fig)
    steps.append('Note: First non-zero digit is 1st signifiant figure,' + \
                 ' going from left to right. Each digit after that is a' + \
                 ' significant figure.')
    answer = []
    answer.append(steps)
    answer.append(round(val, sig_fig-int(floor(log10(val)))-1))

    return question, answer
Exemple #2
0
def qInequalities_template():
    '''Solve inequalities. e.g. 2-3x <= 8.'''
    leftside_section1 = randint(-100,100)
    leftside_section2 = randint(-100,100)
    left_side = leftside_section1 + leftside_section2
    right_side = randint(-100,100)
    equality_type = randint(0,3) #<, <=, >, >=
    question = None 
    x = Symbol('x', real=True) #For 4U Maths use complex=True for ImaginaryNum
    question_str = "Solve "
    if equality_type == 0:
        question = Lt(leftside_section1 + leftside_section2*x, right_side)
    elif equality_type == 1:
        question = Le(leftside_section1 + leftside_section2*x, right_side)
    elif equality_type == 2:
        question = Gt(leftside_section1 + leftside_section2*x, right_side)
    elif equality_type == 3:
        question = Ge(leftside_section1 + leftside_section2*x, right_side)
    question_str += tostring(am.parse(str(question)))

    steps = []
    if leftside_section1 < 0:
        steps.append('Move by +' + str(leftside_section1*-1) + ' to both ' \
                     +'sides')
    else:
        steps.append('Move by -' + str(leftside_section1) + ' to both ' \
                     +'sides')
    steps.append('Divide left and right side by ' + str(leftside_section2))

    answer = []
    answer.append(steps)
    answer.append(tostring(am.parse(str(solve(question, x)))))

    return question_str, answer
 def handleMatch(self, m):
     if markdown.version_info < (2, 1, 0):
         math = asciimathml.parse(m.group(2).strip(), markdown.etree.Element, markdown.AtomicString)
     else:
         math = asciimathml.parse(m.group(2).strip(), markdown.util.etree.Element, markdown.util.AtomicString)
     math.set("xmlns", "http://www.w3.org/1998/Math/MathML")
     return math
Exemple #4
0
def p_matrix_List(p):
    '''expression : '[' INT ',' INT ']' ',' '[' INT ',' INT ']'
   '''
    z = p[2] * p[10] - p[4] * p[8]
    y = tostring(
        asciimathml.parse("[[" + str(p[2]) + "," + str(p[4]) + "],[" +
                          str(p[8]) + "," + str(p[10]) + "]]"))
    x = tostring(asciimathml.parse(str(z)))
    p[0] = z
    print(str(y, "utf-8") + "=" + str(x, "utf-8"))
Exemple #5
0
def qExponentialSameBase_template():
    '''Solves the same base e.g. 2^(2x+1) = 32.'''
    base = choice([2,3,5,7])
    pow_rs = randint(3,6)
    rs = int(pow(base,pow_rs))
    front_num = randint(-100,100)
    while front_num == 0:
        front_num = randint(-100,100)
    lspow = front_num*x+randint(-100,100)
    question = 'Solve ' + tostring(am.parse('%s^(%s) = %s' % (base, lspow, rs)))
    ls_samebase = tostring(am.parse('%s^(%s)' % (base, lspow)))
    rs_samebase = tostring(am.parse('%s^(%s)' % (base, pow_rs)))
    steps = []
    steps.append('Covert right side to be same base as left side. Left side' \
                 ' has a base of: ' + str(base))
    steps.append('As ' + tostring(am.parse('%s^(%s)=%s' % 
                                                 (base, pow_rs, rs))))
    steps.append('Right side is now: ' + tostring(am.parse('%s^(%s)' % 
                                                           (base, pow_rs))))
    steps.append('Therefore ' + ls_samebase + tostring(am.parse('=')) + \
                 rs_samebase)
    steps.append('Therefore solve: ' + tostring(am.parse('%s%s%s' %
                                                        (lspow,'=',pow_rs)))) 
    steps.append('Note: As bases are same the power equates to each other.')
    answer = []
    answer.append(steps)

    if len(solve(Eq(lspow, rs))) > 1:
        answer.append(tostring(am.parse('x = %s' % solve(Eq(lspow, rs))[0])))
    else:
        answer.append(tostring(am.parse('x = %s' % solve(Eq(lspow, rs))[0])))

    return question, answer
Exemple #6
0
 def handleMatch(self, m):
     if markdown.version_info < (2, 1, 0):
         math = asciimathml.parse(
             m.group(2).strip(), markdown.etree.Element,
             markdown.AtomicString)
     else:
         math = asciimathml.parse(
             m.group(2).strip(), markdown.util.etree.Element,
             markdown.util.AtomicString)
     math.set('xmlns', 'http://www.w3.org/1998/Math/MathML')
     return math
Exemple #7
0
def p_Celsius_Fahrenheit_Float(p):
    '''	expression : INT VAR
		           | FLOAT VAR 
	'''
    if p[2] == 'F':
        temp = ((p[1] - 32) / 9.0 * 5.0)
        p[0] = ("%s ° C " % temp)
    elif p[2] == 'C':
        temp = (9.0 / 5.0 * p[1] + 32)
        p[0] = ("%s ° F " % temp)
    y = tostring(asciimathml.parse(str(p[1]) + "° " + str(p[2])))
    x = tostring(asciimathml.parse(str(p[0])))
    print(str(y, "utf-8") + "=" + str(x, "utf-8"))
Exemple #8
0
def p_expression_trigonometry(p):
    '''expression : SIN '(' expression ')'
                | COS '(' expression ')'
                | TAN '(' expression ')' '''
    p[0] = str(p[1]) + str(p[2]) + str(p[3]) + str(p[4])
    if p[1] == 'sin':
        p[0] = (math.sin(p[3]))
    if p[1] == 'cos':
        p[0](math.cos(p[3]))
    if p[1] == 'tan':
        p[0] = (math.tan(p[3]))
    y = tostring(asciimathml.parse(str(p[1]) + str(p[3])))
    x = tostring(asciimathml.parse(str(p[0])))
    print(str(y, "utf-8") + "=" + str(x, "utf-8"))
Exemple #9
0
 def assertRendersTo(self, asciimathml, xmlstring):
     mathml = parse(asciimathml)
     ppa = pretty_print(tostring(mathml))
     ppb = pretty_print('<math><mstyle>%s</mstyle></math>' % xmlstring)
     # open('got.xml', 'w').write(ppa.encode('utf-8'))
     # open('expected.xml', 'w').write(ppb.encode('utf-8'))
     self.assertEquals(ppa, ppb)
Exemple #10
0
 def testSupSub(self):
     self.assertTreeEquals(parse('alpha ^ beta _ gamma'),
         El('math', El('mstyle',
             El('msubsup',
                 El('mi', text=u'\u03b1'),
                 El('mi', text=u'\u03b3'),
                 El('mi', text=u'\u03b2')))))
Exemple #11
0
def convert(_, expr, __, ___, i):
    """Converts expression into MathML

     As of time of writing, MathML is only supported by Firefox and Safari.
     Chrome support has been proposed.
     """
    return tostring(asciimathml.parse(expr)).decode('utf-8')
Exemple #12
0
 def assertRendersTo(self, asciimathml, xmlstring):
     mathml = parse(asciimathml)
     ppa = pretty_print(tostring(mathml))
     ppb = pretty_print('<math><mstyle>%s</mstyle></math>' % xmlstring)
     # open('got.xml', 'w').write(ppa.encode('utf-8'))
     # open('expected.xml', 'w').write(ppb.encode('utf-8'))
     self.assertEquals(ppa, ppb)
Exemple #13
0
def parseMathToML(s):
    """
    Parse a Mathematic expression from a given string and return an XML Element object.
    """
    # TODO: This function should probably be avoided, because Ascii to MathML is usually ambiguous.
    parsedMath = asciimathml.parse(s)
    return parsedMath
Exemple #14
0
 def testNumber(self):
     self.assertTreeEquals(
         parse('3.1415'),
         element_factory(
             'math',
             element_factory('mstyle', element_factory('mn',
                                                       text='3.1415'))))
Exemple #15
0
 def testSymbol(self):
     self.assertTreeEquals(
         parse('alpha'),
         element_factory(
             'math',
             element_factory('mstyle', element_factory('mi',
                                                       text=u'\u03b1'))))
Exemple #16
0
def p_expression_integral(p):
    '''expression : INTEGRAL OF expression'''
    if s.find('^') != -1:
        eq = MathFunctions.formateq(p[3])
    else:
        eq = str(p[3])
    if p[3] is not None:
        eq = (str(MathFunctions.integration(eq, MathFunctions.symbols('x'))))
        eq = MathFunctions.reformateq(eq)
        p[0] = eq

        y = tostring(asciimathml.parse("int" + str(p[3])))
        x = tostring(asciimathml.parse(str(p[0])))
        print(str(y, "utf-8") + "=" + str(x, "utf-8"))
    else:
        pass
Exemple #17
0
 def MathmlToTree(self):
     if self.content:
         self.mathmlObj = parse(self.content)
         for rootMathObj in self.mathmlObj:
             rootId = self.treeArea.AddRoot(text=rootMathObj.tag,
                                            data=rootMathObj)
             self._recursive(rootMathObj, rootId)
Exemple #18
0
 def testUnderOver(self):
     self.assertTreeEquals(parse('sum_alpha^beta'),
         El('math', El('mstyle',
             El('munderover',
                 El('mo', text=u'\u2211'),
                 El('mi', text=u'\u03b1'),
                 El('mi', text=u'\u03b2')))))
Exemple #19
0
def p_expression_derivative(p):
    '''expression : DERIVATIVE OF expression'''
    if s.find('^') != -1:
        eq = MathFunctions.formateq(p[3])
    else:
        eq = str(p[3])
    if p[3] is not None:
        eq = (str(MathFunctions.derivative(eq, MathFunctions.symbols('x'))))
        eq = MathFunctions.reformateq(eq)
        p[0] = eq
        w = tostring(asciimathml.parse('frac{d}{dx}'))
        y = tostring(asciimathml.parse(str(p[3])))
        x = tostring(asciimathml.parse(str(p[0])))
        print(str(w, "utf-8") + str(y, "utf-8") + "=" + str(x, "utf-8"))

    else:
        pass
Exemple #20
0
def qDivInterval_template():
    """Division of Point e.g. The Point P divides the interval joining 
    A(-1, 2) to B(9,3) internally in the ratio 4:1. 
    Find the coordinates of P."""
    # http://www.teacherschoice.com.au/Maths_Library/Analytical%20Geometry/AnalGeom_3.htm

    xa = randint(-10, 10)
    xb = randint(-10, 10)
    ya = randint(-10, 10)
    yb = randint(-10, 10)
    k1 = randint(1, 10)
    k2 = randint(1, 20)
    while yb == ya:
        yb = randint(-10, 10)
    while k1 == k2:
        k2 = randint(1, 20)
    question = "The Point " + tostring(am.parse("P"))
    question += " divides the interval joining " + tostring(am.parse("A(%s,%s)" % (xa, ya)))
    question += " to " + tostring(am.parse("B(%s,%s)" % (xb, yb)))
    question += " internally in the ratio " + tostring(am.parse("%s:%s" % (k1, k2)))

    steps = []
    xp = simplify((k1 * x + k2 * u) / (k1 + k2)).subs(x, xb).subs(u, xa)
    yp = simplify((k1 * y + k2 * t) / (k1 + k2)).subs(y, yb).subs(t, ya)
    steps.append(tostring(am.parse("x_p = ((%s)*(%s) + (%s)*(%s))/(%s+%s)" % (k1, xb, k2, xa, k1, k2))))
    steps.append(tostring(am.parse("y_p = ((%s)*(%s) + (%s)*(%s))/(%s+%s)" % (k1, yb, k2, ya, k1, k2))))
    steps.append("Refer to http://www.teacherschoice.com.au/Maths_Library/Analytical%20Geometry/AnalGeom_3.htm")

    answer = []
    answer.append(steps)
    answer.append(tostring(am.parse("P(%s,%s)" % (xp, yp))))

    return question, answer
Exemple #21
0
 def testUnary4(self):
     self.assertTreeEquals(
         parse('text alpha'),
         element_factory(
             'math',
             element_factory(
                 'mstyle',
                 element_factory('mtext',
                                 element_factory('mi', text=u'\u03b1')))))
Exemple #22
0
 def testUnary(self):
     self.assertTreeEquals(
         parse('sin alpha'),
         element_factory(
             'math',
             element_factory(
                 'mstyle',
                 element_factory('mrow', element_factory('mo', text='sin'),
                                 element_factory('mi', text=u'\u03b1')))))
Exemple #23
0
 def testDivision(self):
     self.assertTreeEquals(
         parse('alpha // beta'),
         element_factory(
             'math',
             element_factory('mstyle', element_factory('mi',
                                                       text=u'\u03b1'),
                             element_factory('mo', text='/'),
                             element_factory('mi', text=u'\u03b2'))))
Exemple #24
0
 def testParens(self):
     self.assertTreeEquals(parse('(alpha + beta) / gamma'),
         El('math', El('mstyle',
             El('mfrac',
                 El('mrow',
                     El('mi', text=u'\u03b1'),
                     El('mo', text='+'),
                     El('mi', text=u'\u03b2')),
                 El('mi', text=u'\u03b3')))))
Exemple #25
0
def qSimpleLimits_template():
    """Limits e.g. lim h->0 sin(h/2)/h"""
    # ans_limit = limit(lambda x: (sin(x/5))/x, 0)

    denominator = randint(2, 10)
    question = "Determine "
    question_str = tostring(am.parse("lim_(x->0)(sin(x/%s))/x" % denominator))
    question += question_str

    steps = []
    working_out_eqn = tostring(am.parse("=lim_(x->0)1/%s*(sin(x/%s))/(x/%s)" % (denominator, denominator, denominator)))
    steps.append(question_str + working_out_eqn)

    answer = []
    answer.append(steps)
    answer.append(tostring(am.parse("1/%s" % denominator)))

    return question, answer
Exemple #26
0
 def testText(self):
     self.assertTreeEquals(
         parse('text{undefined}'),
         element_factory(
             'math',
             element_factory(
                 'mstyle',
                 element_factory('mrow',
                                 element_factory('mtext',
                                                 text='undefined')))))
Exemple #27
0
 def testIncompleteFrac(self):
     self.assertTreeEquals(
         parse('alpha /'),
         element_factory(
             'math',
             element_factory(
                 'mstyle',
                 element_factory('mfrac',
                                 element_factory('mi', text=u'\u03b1'),
                                 element_factory('mo')))))
Exemple #28
0
 def testFrac(self):
     self.assertTreeEquals(
         parse('alpha / beta'),
         element_factory(
             'math',
             element_factory(
                 'mstyle',
                 element_factory('mfrac',
                                 element_factory('mi', text=u'\u03b1'),
                                 element_factory('mi', text=u'\u03b2')))))
Exemple #29
0
 def testSup(self):
     self.assertTreeEquals(
         parse('alpha ^ beta'),
         element_factory(
             'math',
             element_factory(
                 'mstyle',
                 element_factory('msup',
                                 element_factory('mi', text=u'\u03b1'),
                                 element_factory('mi', text=u'\u03b2')))))
Exemple #30
0
 def testUnary2(self):
     self.assertTreeEquals(
         parse('dot alpha'),
         element_factory(
             'math',
             element_factory(
                 'mstyle',
                 element_factory('mover',
                                 element_factory('mi', text=u'\u03b1'),
                                 element_factory('mo', text='.')))))
Exemple #31
0
 def testColor(self):
     self.assertTreeEquals(
         parse('color (blue) x'),
         element_factory(
             'math',
             element_factory(
                 'mstyle',
                 element_factory('mstyle',
                                 element_factory('mi', text=u'x'),
                                 mathcolor='blue'))))
Exemple #32
0
 def testRewriteLRAdditive(self):
     self.assertTreeEquals(
         parse('floor A'),
         element_factory(
             'math',
             element_factory(
                 'mstyle',
                 element_factory('mrow', element_factory('mo', u"\u230A"),
                                 element_factory('mi', 'A'),
                                 element_factory('mo', u"\u230B")))))
Exemple #33
0
 def onAsciiMathAdd(self, evt):
     from xml.etree.ElementTree import tostring
     import asciimathml
     from dialogs import AsciiMathEntryDialog
     entryDialog = AsciiMathEntryDialog(gui.mainFrame)
     if entryDialog.ShowModal() == wx.ID_OK:
         asciimath = entryDialog.GetValue()
         mathml = tostring(asciimathml.parse(asciimath))
         mathml = unicode(mathml)
         MathMlReaderInteraction(mathMl=mathml, interaction_frame=True)
Exemple #34
0
def p_expression_sum(p):
    '''expression : SUM FROM expression TO expression OF expression'''
    lowerBound = p[3]
    highBound = p[5]
    eq1 = str(p[7])
    if s.find('^') != -1:
        eq = MathFunctions.formateq(eq1)
    else:
        eq = str(eq1)
    if lowerBound is not None and highBound is not None and p[7] is not None:
        p[0] = MathFunctions.summation(eq, lowerBound, highBound,
                                       MathFunctions.symbols('x'))
        y = tostring(
            asciimathml.parse("sum_" + str(lowerBound) + "^" + str(highBound) +
                              " " + str(p[7])))
        x = tostring(asciimathml.parse(str(p[0])))
        print(str(y, "utf-8") + "=" + str(x, "utf-8"))

    else:
        pass
Exemple #35
0
 def testUnderOver(self):
     self.assertTreeEquals(
         parse('sum_alpha^beta'),
         element_factory(
             'math',
             element_factory(
                 'mstyle',
                 element_factory('munderover',
                                 element_factory('mo', text=u'\u2211'),
                                 element_factory('mi', text=u'\u03b1'),
                                 element_factory('mi', text=u'\u03b2')))))
Exemple #36
0
def asciimath2latex(input):
    with TemporaryFile() as fMathml:
        mathml = asciimathml.parse(input)
        print(tostring(mathml))
        fMathml.write(tostring(mathml))
        fMathml.seek(0)
        dom = ET.parse(fMathml)
        xslt = ET.parse(XSL_FILENAME)
        transform = ET.XSLT(xslt)
        return transform(dom)
    return ""
Exemple #37
0
 def testQuotedText(self):
     self.assertTreeEquals(
         parse('"time" = "money"'),
         element_factory(
             'math',
             element_factory(
                 'mstyle',
                 element_factory('mrow',
                                 element_factory('mtext', text='time')),
                 element_factory('mo', text='='),
                 element_factory('mrow',
                                 element_factory('mtext', text='money')))))
Exemple #38
0
def p_expression_binop(p):
    '''expression : expression '+' expression
                  | expression '-' expression
                  | expression '*' expression
                  | expression '/' expression
                  | expression POWER expression'''
    if p[2] == '+':
        p[0] = p[1] + p[3]
    elif p[2] == '-':
        p[0] = p[1] - p[3]
    elif p[2] == '*':
        p[0] = p[1] * p[3]
    elif p[2] == '/':
        p[0] = p[1] / p[3]
    elif p[2] == '^' and p[1] != "x" and p[3] != "x":
        p[0] = p[1]**p[3]
    elif p[2] == '^' and p[1] == "x" or p[3] == "x":
        p[0] = str(p[1]) + '^' + str(p[3])

    if p[2] != '^':
        y = tostring(asciimathml.parse(str(p[1])))
        y = y + tostring(asciimathml.parse(str(p[2])))
        y = y + tostring(asciimathml.parse(str(p[3])))

        x = tostring(asciimathml.parse(str(p[0])))

        print(str(y, "utf-8") + "=" + str(x, "utf-8"))
    elif p[1] != "x" and p[3] != "x":
        y = tostring(asciimathml.parse(str(p[1]) + "^" + str(p[3])))
        x = tostring(asciimathml.parse(str(p[0])))
        print(str(y, "utf-8") + "=" + str(x, "utf-8"))
Exemple #39
0
 def OnRewrite(self, evt):
     from xml.etree.ElementTree import tostring
     import asciimathml
     entryDialog = wx.TextEntryDialog(self,
                                      "輸入更改內容:",
                                      value=self.content,
                                      style=wx.TE_MULTILINE | wx.OK
                                      | wx.CANCEL)
     if entryDialog.ShowModal() == wx.ID_OK:
         asciimath = entryDialog.GetValue()
         mathMl = tostring(asciimathml.parse(asciimath))
         self.content = mathMl
         self.modelBindView()
Exemple #40
0
 def tesRewriteLRNested(self):
     self.assertTreeEquals(
         parse('floor abs A'),
         element_factory(
             'math',
             element_factory(
                 'mstyle',
                 element_factory(
                     'mrow', element_factory('mo', u"\u230A"),
                     element_factory('mrow', element_factory('mo', '|'),
                                     element_factory('mi', 'A'),
                                     element_factory('mo', '|')),
                     element_factory('mo', u"\u230B")))))
Exemple #41
0
def qSeconDiffInvolvingInverseTan_template():
    """If y = tan^-1(x^2), find d^2y/dx^2."""

    x_pow = randint(2, 5)
    question = "If " + tostring(am.parse("y=ta"))
    question += tostring(am.parse("n^(-1)(x^%s)," % x_pow))
    question += " find " + tostring(am.parse("(d^2y)/(dx^2)."))

    steps = []
    first_diff = (x_pow * x) / (1 + x ** x_pow)
    second_diff = diff(first_diff)
    second_diff_str = str(second_diff).replace("**", "^")
    val_regex = re.compile("/")
    val2_regex = re.compile("\+")
    second_diff_str_mod = val_regex.split(second_diff_str)
    second_diff_str_mod2 = val2_regex.split(second_diff_str_mod[1])
    steps.append(tostring(am.parse(" (dy)/(dx)= %s" % str(first_diff).replace("**", "^"))))

    answer = []
    answer.append(steps)
    answer.append(
        tostring(
            am.parse(
                " (d^2y)/(dx^2)= (%s)/(%s+%s)+(%s)/(%s)"
                % (
                    second_diff_str_mod[0],
                    second_diff_str_mod2[0],
                    second_diff_str_mod2[1],
                    second_diff_str_mod2[2],
                    second_diff_str_mod[2],
                )
            )
        )
    )

    return question, answer
Exemple #42
0
def qSimpleTSubstitutionCos_template():
    """t substitution
    e.g. If t = tan x/2, express as simply as possible in terms of t, (1-cosx)/(1+cosx)"""

    front_num = randint(-3, 3)
    while front_num == 0:
        front_num = randint(-3, 3)

    denom_positive = randint(0, 1)

    question = "If " + tostring(am.parse("t=tan(x/2)"))
    question += " express as simply as possible in terms of " + tostring(am.parse("t,"))
    question_eqn = None
    question_eqn_str = None
    eqn_sub_top = None
    if denom_positive == 1:
        eqn_sub_top = front_num + cos(x)
        eqn_sub_bott = front_num - cos(x)
        question_eqn = (eqn_sub_top) / (eqn_sub_bott)
        question_eqn_str = tostring(am.parse("(%s+cos(x))/(%s-cos(x))" % (front_num, front_num)))
    else:
        eqn_sub_top = front_num - cos(x)
        eqn_sub_bott = front_num + cos(x)
        question_eqn = (eqn_sub_top) / (eqn_sub_bott)
        question_eqn_str = tostring(am.parse("(%s-cos(x))/(%s+cos(x))" % (front_num, front_num)))

    question += " " + question_eqn_str

    u = (1 - t ** 2) / (1 + t ** 2)
    eqn_sub = question_eqn.subs(cos(x), u)
    eqn_sub_str = str(eqn_sub).replace("**", "^")
    eqn_top = simplify(expand(eqn_sub_top.subs(cos(x), u)))
    eqn_top_str = str(eqn_top).replace("**", "^")
    eqn_bott = simplify(expand(eqn_sub_bott.subs(cos(x), u)))
    eqn_bott_str = str(eqn_bott).replace("**", "^")
    eqn_simplified = simplify(eqn_sub)
    eqn_simplified_str = str(eqn_simplified).replace("**", "^")

    steps = []
    steps.append(question_eqn_str + tostring(am.parse("=%s" % (eqn_sub_str))))
    steps.append(tostring(am.parse("=(%s)/(%s)" % (eqn_top_str, eqn_bott_str))))

    answer = []
    answer.append(steps)
    answer.append(tostring(am.parse("%s" % eqn_simplified_str)))

    return question, answer
Exemple #43
0
def convert_to_mathml():
    args = parse_args()
    standard_in = False
    in_file = args.in_file
    if isinstance(in_file, io.TextIOWrapper):
        the_string = sys.stdin.read()
        xml_tree = etree.fromstring(the_string)
    else:
        xml_tree = etree.ElementTree().parse(in_file)
    for element in xml_tree.iter():
        if element.tag == 'math' or element.tag == 'math_block':
            mathml_tree  = asciimathml.parse(element.text)
            mathml_tree.set("title", element.text)
            mathml_tree.set("xmlns", "http://www.w3.org/1998/Math/MathML")
            element.append(etree.XML(etree.tostring(mathml_tree)))
            element.text = ''
    string_tree = etree.tostring(xml_tree, encoding="utf-8") 
    if sys.version_info < (3,):
        sys.stdout.write(string_tree)
    else:
        sys.stdout.write(string_tree.decode())
 def endElementNS(self, name, qname):
       ns = name[0]
       el_name = name[1]
       if (el_name == 'math_block' and  self.__mathml == 'ascii') or (el_name == 'math' and self.__mathml == 'ascii'):
           raw_tree  = asciimathml.parse(self.__characters)[0]
           math_tree = Element('math', title="%s" % self.__characters, xmlns="http://www.w3.org/1998/Math/MathML")
           math_tree.append(raw_tree)
           string_tree = tostring(math_tree, encoding="utf-8") 
           sys.stdout.write(string_tree.decode('utf8'))
           """
           if sys.version_info < (3,):
               print(type(string_tree))
               print()
               sys.stdout.write(string_tree.decode('utf8'))
               # sys.stdout.write(line.encode('utf8'))
           else:
               sys.stdout.write(string_tree.decode())
           """
           self.__characters = ''
       elif (el_name == 'math_block' and  self.__mathml == 'latex') or (el_name == 'math' and self.__mathml == 'latex'):
           raw_tree = self.__tralics()
           if raw_tree == None:
               self.__write_text()
           else:
               raw_tree = raw_tree[0]
               math_tree = Element('math', title="%s" % self.__characters, xmlns="http://www.w3.org/1998/Math/MathML")
               math_tree.append(raw_tree)
               string_tree = tostring(math_tree, encoding="utf-8").decode() 
               sys.stdout.write(string_tree)
               self.__characters = ''
       elif el_name == 'raw' and self.__raw:
           self.__write_text(raw = True)
       else:
           self.__write_text()
       if ns:
           sys.stderr.write('Should not be namespace "%s" here\n' % (ns))
           sys.exit(1)
           sys.stdout.write('</ns1:%s>' % el_name)
       else:
           sys.stdout.write('</%s>' % el_name)
Exemple #45
0
def qExpDifferentiation_template():
    '''Differeniate exponential e.g. diff e^(2x^3+2)'''
    rand_power = randint(2,100) #Can't do -ve as this is calculated differently
    front_num = randint(-100,100)
    while front_num == 0:
        front_num = randint(-100,100)
    end_num = randint(-100,100)
    while front_num == 0:
        end_num = randint(-100,100)
    if end_num < 0:
        question = 'Differentiate ' + tostring(am.parse('e^(%sx^(%s)%s)' 
                                                        % (front_num,
                                                           rand_power,
                                                           end_num)))
    else:
        question = 'Differentiate ' + tostring(am.parse('e^(%sx^(%s)+%s)' 
                                                        % (front_num,
                                                           rand_power,
                                                           end_num)))
    question += ' with respect to ' + tostring(am.parse('x'))

    steps = []
    diff_top = diff(front_num*x**(rand_power)+end_num)
    if end_num < 0:
        steps.append('Differentiate %s normally' % tostring(am.parse('%sx^(%s)%s' 
                                                                     % (front_num, 
                                                                        rand_power,
                                                                        end_num))))
    else:
        steps.append('Differentiate %s normally' % tostring(am.parse('%sx^(%s)+%s' 
                                                                     % (front_num, 
                                                                        rand_power,
                                                                        end_num))))
    steps.append('This will give %s which is mulitiplied to original question' 
                 % tostring(am.parse(str(diff_top).replace("**","^"))))
    answer = []
    answer.append(steps)
    diff_val = diff(exp(front_num*x**(rand_power)+end_num))
    answer.append(tostring(am.parse(str(diff_val).replace("**","^").
                                   replace("exp", "e^"))))

    return question, answer
Exemple #46
0
def qLogDifferentiation_template():
    '''Differeniate log(e) e.g. diff ln(5*x+2)'''
    first_val = randint(-100,100)
    while first_val == 0:
        first_val = randint(-100,100)
    second_val = randint(-100,100)
    if second_val < 0:
        question = 'Differentiate ' + tostring(am.parse('ln((%sx%s))' 
                                                        % (first_val, 
                                                           second_val))) 
    else:
        question = 'Differentiate ' + tostring(am.parse('ln((%sx+%s))' 
                                                        % (first_val, 
                                                           second_val))) 
    question += ' with respect to ' + tostring(am.parse('x'))

    steps = []
    diff_inside = diff(first_val*x+second_val)
    if second_val < 0:
        steps.append('Differentiate %s normally' % tostring(am.parse('%sx%s' %
                                                   (first_val, second_val))))
    else:
        steps.append('Differentiate %s normally' % tostring(am.parse('%sx+%s' %
                                                   (first_val, second_val))))
    steps.append('This will give %s which goes as numerator' % str(diff_inside))
    if second_val < 0:
        steps.append('%s goes as denominator' % tostring(am.parse('%sx%s' %
                                                   (first_val, second_val))))
    else:
        steps.append('%s goes as denominator' % tostring(am.parse('%sx+%s' %
                                                   (first_val, second_val))))
    answer = []
    answer.append(steps)
    answer.append(tostring(am.parse(str(diff(ln(first_val*x+second_val))))))

    return question, answer
Exemple #47
0
def qIntegrationNegativePower_template():
    '''Integration involving a negative power e.g. 1/x^2.'''
    '''Reason why this is asked is because students mistake this for ln()'''
    pow_val = randint(2,9)
    front_num = randint(-100,100)
    #Note we remove the front number if -1 or 1 for time being to avoid logic
    while front_num <= 1 and front_num >=-1: 
        front_num = randint(-100,100)
    question = "Find " + tostring(am.parse('int1/(%sx^%s)dx'% (str(front_num),
                                                               str(pow_val))))

    steps = []
    num_log_diff = diff(front_num*x**pow_val)
    true_log_integrate = tostring(am.parse('int(%s)/(%sx^%s)dx'%
                                           (str(num_log_diff).
                                            replace("**", "^"),
                                            str(front_num),
                                            str(pow_val)))) 
    steps.append("This is not a logarithmic integration.")
    steps.append("The reason is that the diff of the bottom x value should " + \
                 "go on top which is the premise behind a logarithmic " + \
                 "integration but the question does not show this. If you " + \
                 "see " + true_log_integrate + " then it is.")
    group_integrate = tostring(am.parse('int(%sx)^-%sdx'% (str(front_num),
                                                           str(pow_val)))) 
    steps.append("Integrate this normally as: " + group_integrate + \
                 " which is the same as " + \
                 tostring(am.parse('int1/(%sx^%s)dx' % (str(front_num),
                                                        str(pow_val)))))
    steps.append("Integrating this will be: [1 / (diff of " +
                 tostring(am.parse("%sx*-%s" % (str(front_num),
                                                str(pow_val)))) + 
                 ")]" + tostring(am.parse("*(%sx)^(-%s+1)" % (str(front_num),
                                                              str(pow_val)))))

    answer = []
    answer.append(steps)
    ans = integrate(1/(front_num*x**pow_val))
    answer.append(tostring(am.parse(str(ans).replace("**","^"))))

    return question, answer
Exemple #48
0
def qSimpleBatchProbability_template():
    '''Simple Batch Probability problem.'''
    num_items = randint(100, 20000)
    defective_prob = float(randint(1,100))/1000 #Want it to be 0.001 accuracy
    question = "A batch of " + str(num_items) + " items is examained. " + \
            "The probability of an item in this batch being defective is " + \
            str(defective_prob)
    question += ". How many items from this batch are defective?"

    steps = []
    prob_eqn = tostring(am.parse("Pr(E)=(n(E))/(n(S))"))
    prob_word_eqn = tostring(am.parse("Probability(Event)=(" + \
                                      "# of Events)/(" + \
                                      "# of Sample Space)"))
    steps.append("The probability of defectiveness is governed by the"+ \
                 "following equation: " + prob_word_eqn + " known as: " + \
                 prob_eqn)
    steps.append("As we are given " + tostring(am.parse("Pr(E)=%s" %
                                                        str(defective_prob))) +\
                 " which is the defective probability ")
    steps.append("Also we are given " + tostring(am.parse("n(s)=%s" %
                                                        str(num_items))) + \
                 " which is the number of items in the batch (sample space) ")
    steps.append("Therefore we need to find " + tostring(am.parse("n(E)=Pr" + \
                                                                  "(E)*n(s)")))
    steps.append("This gives " + tostring(am.parse("n(E)=%s*%s" %
                                                   (str(defective_prob),
                                                    str(num_items))))) 
    steps.append("This gives %s" % str(float(num_items)*defective_prob))
    steps.append("Round to nearest whole number as you cannot have fraction")

    answer = []
    answer.append(steps)
    ans = int(round(float(float(num_items)*defective_prob),0))
    answer.append(tostring(am.parse(str(ans))))

    return question, answer
Exemple #49
0
def qSimplifyBinomial_template():
    '''Simplify Binomial e.g. Simplify n^2-25/n-5.'''
    base = choice([2,3,5,7])
    pow_base = pow(base, 2)
    numerator = x**2-int(pow_base)
    denominator = x-base
    question = 'Simplify ' + tostring(am.parse('(x^2-%s)/(x-%s)' %
                                               (int(pow_base), base)))

    steps = []
    steps.append('Covert numerator to binomial to match denominator.')
    binomial = tostring(am.parse('x^2-%s' % (int(pow_base))))
    expanded_binomial = tostring(am.parse('(x-%s)(x+%s)' % (base,base)))
    steps.append('As '+ binomial + ' is the same as ' + expanded_binomial)
    steps.append('Therefore ' + tostring(am.parse('((x-%s)(x+%s))/(x-%s)' %
                                                  (base,base,base))))
    steps.append('Cancel '+ tostring(am.parse('(x-%s)' %(base))) + 
                 ' from denominator and numerator')
    answer = []
    answer.append(steps)
    answer.append(tostring(am.parse(str(simplify(numerator/denominator)))))

    return question, answer
Exemple #50
0
 def testSub(self):
     self.assertTreeEquals(parse('alpha _ beta'),
         El('math', El('mstyle',
             El('msub',
                 El('mi', text=u'\u03b1'),
                 El('mi', text=u'\u03b2')))))
Exemple #51
0
 def testDivision(self):
     self.assertTreeEquals(parse('alpha // beta'),
         El('math', El('mstyle',
             El('mi', text=u'\u03b1'),
             El('mo', text='/'),
             El('mi', text=u'\u03b2'))))
Exemple #52
0
 def testIncompleteFrac(self):
     self.assertTreeEquals(parse('alpha /'),
         El('math', El('mstyle',
             El('mfrac',
                 El('mi', text=u'\u03b1'),
                 El('mo')))))
Exemple #53
0
 def testQuotedText(self):
     self.assertTreeEquals(parse('"a \\" \\\\ b"'),
         El('math', El('mstyle',
             El('mrow', El('mtext', text='a " \ b')))))
Exemple #54
0
 def testText(self):
     self.assertTreeEquals(parse('text{undefined}'),
         El('math', El('mstyle',
             El('mrow', El('mtext', text='undefined')))))
Exemple #55
0
 def testFrac(self):
     self.assertTreeEquals(parse('alpha / beta'),
         El('math', El('mstyle',
             El('mfrac',
                 El('mi', text=u'\u03b1'),
                 El('mi', text=u'\u03b2')))))
Exemple #56
0
 def testSymbol(self):
     self.assertTreeEquals(parse('alpha'), El('math', El('mstyle', El('mi', text=u'\u03b1'))))
Exemple #57
0
 def testNumber(self):
     self.assertTreeEquals(parse('3.1415'), El('math', El('mstyle', El('mn', text='3.1415'))))
Exemple #58
0
 def testEmpty(self):
     self.assertTreeEquals(parse(''), El('math', El('mstyle')))
Exemple #59
0
 def testUnary4(self):
     self.assertTreeEquals(parse('text alpha'),
         El('math', El('mstyle',
             El('mtext',
                 El('mi', text=u'\u03b1')))))
Exemple #60
0
 def testBinary(self):
     self.assertTreeEquals(parse('frac alpha beta'),
         El('math', El('mstyle',
             El('mfrac',
                 El('mi', text=u'\u03b1'),
                 El('mi', text=u'\u03b2')))))