oyster
oyster

Reputation: 567

Failed to show calculation steps with sympy and markdown

Question

I want to show the steps of calculation (for example, in text book) in markdown file which is created by a python code. here is what I need in original python code

from sympy import *

angle = 60    # this will be changed to created different markdown files

theta = symbols('ss')
x = symbols('xx')

a = Matrix([[cos(theta), -sin(theta), 0], [sin(theta), cos(theta), 0], [0, 0, 1]])
b = Matrix([[x, 0, 0], [0, x, 1], [0, 0, 0]])

print(
'$$',
latex(a), latex(b), '=',   # step 1
latex(a).replace('ss', latex(rad(angle))), latex(b).replace('xx', '2'), '=', # step 2
latex(a.subs('ss', rad(60))), latex(b.subs('xx', '2')), '=', # step 3
latex((a*b).subs({'ss': rad(60), 'xx':2}).evalf(2)), # step 4
'$$'
)

you may find that step 1 lists the common matrix, step 2 substitutes the element of matrix by given value, step 3 calculates/simplifies the matrix and step 4 evaluates the matrix elements to float form.

There are too many calls of latex which make the code too long and hard to read.

First try

I write

from sympy import *

class T_Rotate(object):
    def __init__(self, theta):
        self.eq = Matrix([[cos(theta), -sin(theta), 0], [sin(theta), cos(theta), 0], [0, 0, 1]])
        self.str = latex(self.eq)

    def __mul__(self, mat):
        return self.eq * mat

    def __rmul__(self, mat):
        return  mat * self.eq

a = T_Rotate(60)
b = Matrix([[1, 0, 0], [0, 1, 1], [0, 0, 0]])

print('$$a*b = %s * %s = %s$$' % (a.str, latex(b), latex(a*b)))

print('$$b * a = %s * %s = %s$$' % (latex(b), a.str, latex(b*a)))

but above a * b is a wrong answer which is a 3*3 matrix but whose elements are all 3*3 matrix!

so, what is the problem?

Further thought

In case the above be fixed, there are still call of latex function. Any hints to wrap sympy expression so that the python code can be more terse?

thanks

Upvotes: 2

Views: 357

Answers (1)

oyster
oyster

Reputation: 567

Now I wrote https://github.com/retsyo/expand_expression to answer the post partly. But I am also still seeking for a more common method without supplying every functions by the user

I released it for it can help others. Here is a example:

If you have defined a function, then you can use it like

T1 = T_Rotate('pi/6 + pi/2', useRad=True)
fOut.write(latexExpression('T1'))

Is it easy? I think so.

Upvotes: 1

Related Questions