我的问题的实质如下:我在一个名为sol_expr的函数中构建一个字符串变量。当我打印(sol_expr)时,结果看起来与我需要的完全一样,即:
'%s = %s \\text{ or } %s' %(sym.latex(expr3), sym.latex(sol[0]),sym.latex(sol[1]))
但是,当我使用以下代码
display(Math('%s' %(sol_expr) ))
我得到的结果是:'
让我感到困惑的是,下面的代码正是我想要的:
sol_expr = '%s = %s \\text{ or } %s' %(sym.latex(expr3), sym.latex(sol[0]),sym.latex(sol[1]))
display(Math('%s' %(sol_expr) ))
我不明白区别。谁能发现盲点?
为完整起见,完整的代码
import sympy as sym
import numpy as np
from IPython.display import display, Math, Latex
sym.init_printing() # allows the Latex rendering in Markdown cells
# function to construct the expression to be used with the Display function
def construct_sol_expr(nr_of_sols):
# construct statement part
dyn_expr = '%s = %s'
for n in range(1,nr_of_sols):
dyn_expr = dyn_expr + r' \\text{ or } %s'
dyn_expr = "'%s'" %(sym.latex(dyn_expr))
# construct parameter part
par_expr = ''
for p in range(0,nr_of_sols):
# if there is more than 1 parameter neccessary, you need a comma
if p != nr_of_sols-1:
comma = ','
else:
comma = ''
par_expr = par_expr + 'sym.latex(sol[' + str(p) + '])' + comma
# tie it together
sol_expr = dyn_expr + ' %(' + 'sym.latex(expr3), ' + par_expr + ')'
return sol_expr, dyn_expr, par_expr
q = sym.symbols('q')
expr1 = 3*q + 4/q + 3
expr2 = 5*q + 1/q + 1
expr3 = expr1 -expr2
sol = sym.solve(expr3, q)
sol_expr, dyn_expr, par_expr = construct_sol_expr(len(sol))
print(sol_expr)
# '%s = %s \\text{ or } %s' %(sym.latex(expr3), sym.latex(sol[0]),sym.latex(sol[1]))
# Uncomment to see my issue
# sol_expr = '%s = %s \\text{ or } %s' %(sym.latex(expr3), sym.latex(sol[0]),sym.latex(sol[1]))
display(Math('%s' %(sol_expr) ))
答案 0 :(得分:0)
这就是我想要完成的。
import sympy as sym
import numpy as np
from IPython.display import display, Math, Latex
sym.init_printing() # allows the Latex rendering in Markdown cells
# Function to construct the expression to be used with the Display function
def construct_sol_expr(expr, sol):
# The trick is to build the latex statement right away instead if constructing it with %s elements
# construct the dynamic solution(s) part of the latex expression
dyn_expr = ''
for d in range(0,len(sol)):
# if there is more than 1 parameter neccessary, you need a separator
if d != len(sol)-1:
sprtr = '\\quad \\text{ or } \\quad '
else:
sprtr = ''
sol_d = sym.latex(sol[d]) # get the dth entry in the solution list
sol_Nd = sym.latex(sym.N(sol[d])) # get the dth entry in the solution list
dyn_expr = dyn_expr + sol_d + ' = ' + sol_Nd + sprtr
# tie it together
sol_expr = str(sym.latex(expr)) + '\\quad = \\quad' + str(dyn_expr)
return sol_expr
q = sym.symbols('q')
expr1 = 3*q + 4/q + 3
expr2 = 5*q + 1/q + 1
expr3 = expr1 -expr2
sol = sym.solve(expr3, q)
sol_expr = construct_sol_expr(expr3, sol)
display(Math(sol_expr))
希望它对其他人也有帮助