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