本文整理汇总了Python中sympy.latex函数的典型用法代码示例。如果您正苦于以下问题:Python latex函数的具体用法?Python latex怎么用?Python latex使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了latex函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: solution_statement
def solution_statement(self):
lines = solutions.Lines()
if self._qp['question_type'] == 'mean':
lines += r'$E(X) = \sum\limits_{{i=1}}^{{n}} x_{{i}} \times Pr(X = x_{{i}})$'
lines += r'$= {expectation_of_x} = {answer}$'.format(
expectation_of_x=expressions.discrete_expectation_x(self._qp['prob_table']),
answer=self._qp['answer']
)
elif self._qp['question_type'] == 'variance':
lines += r'$Var(X) = E(X^2) - (E(X))^2$'
lines += r'$= [{expectation_of_x_squared}] - [{expectation_of_x}]^2$'.format(
expectation_of_x_squared=expressions.discrete_expectation_x_squared(self._qp['prob_table']),
expectation_of_x=expressions.discrete_expectation_x(self._qp['prob_table'])
)
expectation_of_x = prob_table.expectation_x(self._qp['prob_table'])
expectation_of_x_squared = prob_table.expectation_x(self._qp['prob_table'], power=2)
lines += r'$= {expectation_of_x_squared} - {expectation_of_x}^2 = {answer}$'.format(
expectation_of_x_squared=sympy.latex(expectation_of_x_squared),
expectation_of_x=sympy.latex(expectation_of_x),
answer=sympy.latex(self._qp['answer'])
)
elif self._qp['question_type'] == 'mode':
lines += r'${answer}$'.format(
answer=prob_table.mode(self._qp['prob_table'])
)
return lines.write()
示例2: relation
def relation(interval_or_relation, var=x):
"""Return LaTeX that represents an interval or a relation as a chained inequality.
e.g. [1, 5] --> 1 < x < 5
"""
if isinstance(interval_or_relation, (sympy.StrictLessThan, sympy.LessThan, sympy.StrictGreaterThan, sympy.GreaterThan)):
interval = functions.relation_to_interval(interval_or_relation)
else:
interval = interval_or_relation
if isinstance(interval_or_relation, sympy.Union):
raise NotImplementedError('unions are not yet supported')
if interval.left == -sympy.oo and interval.right == sympy.oo:
return r'{0} < {1} < {2}'.format(sympy.latex(-sympy.oo), sympy.latex(var), sympy.latex(sympy.oo))
elif interval.left == -sympy.oo:
operator = r'<' if interval.right_open else r'\le'
return r'{0} {1} {2}'.format(sympy.latex(var), operator, sympy.latex(interval.right))
elif interval.right == sympy.oo:
operator = r'>' if interval.left_open else r'\ge'
return r'{0} {1} {2}'.format(sympy.latex(var), operator, sympy.latex(interval.left))
else:
left_operator = r'<' if interval.left_open else r'\le'
right_operator = r'<' if interval.right_open else r'\le'
return r'{0} {1} {2} {3} {4}'.format(
sympy.latex(interval.left),
left_operator,
sympy.latex(var),
right_operator,
sympy.latex(interval.right)
)
示例3: print_latex
def print_latex():
# edo_main()
for i in range(1, 7):
Respostas[i] = sympy.nsimplify(Respostas[i], rational=True, tolerance=0.05).evalf(prec)
# 0- Raizes; 1- Forma Natural da respsota; 2- Resposta Natural;
# 3- Resposta Particular; 4- Resposta Transitoria; 5- Respsota Forcada
# 6- Resposta Completa; 7-Sinal de entrada x(t); 8 - eq
###
eqDiferencialEntradaLatex = latex(Respostas[8])
##Perfumaria
dif = 0.9 - 0.77
xdif = -0.15
font = {"family": "Sans", "weight": "normal", "size": 18}
plt.rc("font", **font)
##Obtendo as respostas em Latex
RespostasEmLatex = [0] * (len(Respostas))
raizEmLatex = [0] * (len(Respostas[0]))
str_raizLatex = ""
for i in range(len(Respostas[0])):
raizEmLatex[i] = "$" + str(latex(Respostas[0][i])) + "$"
for i in range(len(raizEmLatex)):
rn = "r" + str(i + 1) + " = "
rn = "$" + str(latex(rn)) + "$"
str_raizLatex = str_raizLatex + "\t" + rn + raizEmLatex[i]
##print len(RespostasEmLatex)
for i in range(len(Respostas)):
RespostasEmLatex[i] = "$" + str(latex(Respostas[i])) + "$"
# print RespostasEmLatex
# xTLatex = '$' + latex(xT) +'$'
###Preparando para imprimir
log_figure = plt.figure("Representacao", facecolor="white")
ax1 = plt.axes(frameon=False)
ax1.get_xaxis().tick_bottom()
ax1.get_xaxis().set_visible(False)
ax1.axes.get_yaxis().set_visible(False)
for i in range(0, 8, 1):
plt.axhline(0.86 - dif * i, xmin=-5, xmax=5, color="black", lw=0.2, linestyle=":")
# log_figure.figure("Forma_Representativa:")
plt.title("")
plt.text(xdif, 0.89, "Eq dif: 0=" + ur"$" + eqDiferencialEntradaLatex + "$")
plt.text(xdif, 0.89 - dif, "Forma Natural:" + ur"" + RespostasEmLatex[1])
plt.text(xdif, 0.9 - 2 * dif, "yn(t) = " + ur"" + RespostasEmLatex[2])
plt.text(xdif, 0.9 - 3 * dif, "ypar(t) = " + ur"" + RespostasEmLatex[3])
plt.text(xdif, 0.9 - 4 * dif, "ytran(t) = " + ur"" + RespostasEmLatex[4])
plt.text(xdif, 0.9 - 5 * dif, "yfor(t) = " + ur"" + RespostasEmLatex[5])
plt.text(xdif, 0.9 - 6 * dif, "yc(t) = " + ur"" + RespostasEmLatex[6])
plt.text(xdif, 0.9 - 7 * dif, "x(t) = " + ur"" + RespostasEmLatex[7])
plt.text(xdif, 0.9 - 8 * dif, "Raiz(es): " + ur"" + str_raizLatex)
plt.subplots_adjust(left=0.11, bottom=0.08, right=0.50, top=0.88, wspace=0.22, hspace=0.21)
##log_figure.set_size_inches(19.2,10.8)
# log_figure.show()
plt.show()
return log_figure
示例4: formula
def formula(quantity):
""" returns error formula of quantity as latex code
Args:
quantity: Quantity object
Return:
latex code string of error formula
"""
assert isinstance(quantity, Quantity)
if quantity.error_formula is None:
raise ValueError("quantity '%s' doesn't have an error formula." % quantity.name)
formula = quantity.error_formula
if isinstance(formula,str):
return formula
else:
# replace "_err" by sigma function
sigma = Function("\sigma")
for var in formula.free_symbols:
if var.name[-4:] == "_err":
formula = formula.subs(var, sigma( Symbol(var.name[:-4], **var._assumptions)))
latex_code = latex(sigma(quantity)) + " = " + latex(formula)
form_button, form_code = pytex.hide_div('Formula', '$%s$' % (latex_code) , hide = False)
latex_button, latex_code = pytex.hide_div('LaTex', latex_code)
res = 'Error Formula for %s<div width=20px/>%s%s<hr/>%s<br>%s' % (
'$%s$' % latex(quantity), form_button, latex_button, form_code, latex_code)
return render_latex(res)
示例5: baseparms_pretty_latex
def baseparms_pretty_latex(delta,Pb,Pd,Kd):
base_latex = []
delta_b = Pb.T * delta
delta_d = Pd.T * delta
n_b = len(delta_b)
n_d = len(delta_d)
for i in range(n_b):
_latex = latex( delta_b[i] )
l = []
for j in range(n_d):
c = Kd[i,j]
if c == -1 or c == 1:
_latex += ' ' + ('+ ' if c > 0 else'') + latex( c * delta_d[j] )
elif c != 0 and j not in l:
ll = []
for jj in range(j,n_d):
cc = Kd[i,jj]
if cc == c:
l.append(jj)
ll.append(delta_d[jj])
p = (' \, ( ',' ) ') if (len(ll) > 1) else (' \, ','')
ll_sum = ' + '.join( [ latex( lli ) for lli in ll] )
_latex += ' ' + ('+ ' if c > 0 else'') + latex( c.n() ) + p[0] + ll_sum + p[1]
base_latex.append(_latex)
return base_latex;
示例6: solution_statement
def solution_statement(self):
lines = solutions.Lines()
ball_combinations = itertools.combinations(self._qp['items'], self._qp['n_selections'])
valid_total_sum_combinations = [i for i in ball_combinations if sum(i) == self._qp['sum']]
# e.g. Pr(sum = 14) = 3! * Pr(ball1 = 3 and ball2 = 5 and ball3 = 6)
lines += r'$Pr(\text{{sum}} = {sum}) = {sum_of_probabilities}$'.format(
sum=self._qp['sum'],
sum_of_probabilities=expressions.sum_combination_probabilities(valid_total_sum_combinations)
)
probability_of_a_single_combination = self.single_combination_probability()
prob_instance = r'{n_valid_permutations} \times {probability_of_a_single_combination}'.format(
n_valid_permutations=math.factorial(self._qp['n_selections']),
probability_of_a_single_combination=sympy.latex(probability_of_a_single_combination)
)
# e.g. = 6 * (1/120) + 6 * (1/120)
lines += r'$= {probabilities_sum}$'.format(
probabilities_sum=' + '.join([prob_instance] * len(valid_total_sum_combinations))
)
answer = probability_of_a_single_combination * math.factorial(self._qp['n_selections']) * len(valid_total_sum_combinations)
# e.g. = 1/20
lines += r'$= {answer}$'.format(answer=sympy.latex(answer))
return lines.write()
示例7: table_groesse
def table_groesse(expr,variables,container,name,formula=False,einheit="default"):
(X,expr,Sexpr)=eval_expr(expr,variables,container,name)
if einheit!="default":
X.convert_einheit(einheit)
x=ur"\bigskip"
if formula==True:
x+=ur"\begin{equation*} "+name+" = "+sy.latex(expr)+"\end{equation*}"
x+=ur"\begin{equation*} S"+name+" = "+sy.latex(Sexpr)+"\end{equation*}"
s=ur""
s2=ur""
if X.x.dimensionality.string != "dimensionless":
x+=ur"S"+name+" = "+sy.latex(Sexpr)+ur"\\"
s=ur""
s2=ur""
if X.x.dimensionality.string != "dimensionless":
s+=name+" in "+str(X.x.dimensionality.string)
else:
s+=name
for k in X.x.magnitude:
s+="& %.3f " % k
s2+="r|"
s+=ur"\\ \hline "
if X.Sx.dimensionality.string!= "dimensionless":
s+="S"+name+" in "+str(X.Sx.dimensionality.string)
else:
s+="S"+name
for k in X.Sx.magnitude:
s+="& %.3f " % k
s+=ur"\\ \hline"
x+=ur"""\normalsize \vspace{3 mm}
\begin{tabular}{| l | """+s2+"""}
\hline
"""+s+ur"""
\end{tabular} \\ \bigskip """
return x
示例8: arc_length_explain
def arc_length_explain(self, start, stop, a_type = None,
explanation_type=None, preview = None):
if a_type is None:
a_type = self.a_type
v = self.v_
u = self.u
start = sym.sympify(start)
stop = sym.sympify(stop)
if explanation_type is None:
explanation_type = self.kwargs.get('explanation_type', 'simple')
if preview is None:
preview = self.kwargs.get('preview', False)
explanation = ArcLengthProb(path='arc_length/explanation',
a_type = a_type,
explanation_type = explanation_type,
preview = preview).explain()
explanation += """
<p>
For this problem the curve is $_C$_ is given by $_%s$_
with the independent variable being $_%s$_ on the interval
$_[%s,%s]$_. So the arc length is
$$s =\\int_{%s}^{%s} \sqrt{1+\\left(\\frac{d%s}{d%s}\\right)^2}\,d%s$$
$$\\frac{d%s}{d%s} = %s = %s$$
\\begin{align}
\\sqrt{1 + \\left(%s\\right)^2} &= \\sqrt{%s} \\\\
&= \sqrt{\\left(%s\\right)^2} = %s
\\end{align}
</p>
"""%tuple(map(lambda x: sym.latex(x).replace("\\log","\\ln"),
[sym.Eq(v, self.v), u, start, stop, start, stop,
v, u, u, v, u,
self.Dv, self.dv, self.dv, 1 + (self.dv**2).expand(),
self.ds, self.ds]))
aa = [sym.latex(self.arc_length(start, stop,'integral')),
"\\left." + sym.latex(self.Ids).replace('\\log', '\\ln') +
"\\right|_{%s=%s}^{%s=%s}"%(u, start, u, stop),
sym.latex(self.arc_length(start, stop,'exact')).replace("\\log", "\\ln") +
'\\approx %.3f'%(self.arc_length(start, stop,'numeric'))]
# Add self.numeric / self.anti
explanation += """
<p>
Thus the arclength is given by
%s
</p>
"""%(tools.align(*aa))
#
return explanation
示例9: __str__
def __str__(self):
s = ""
xi = [r'\vec i', r'\vec j', r'\vec k']
phi = r"\phi(\vec r)"
for key in sorted(self.stateMap.keys()):
s += self.beginTable()
qNums = str(self.stateMap[key]).strip("]").strip("[")
genericFactor = self.genericFactor(self.stateMap[key])
s += "$\phi_{%d} \\rightarrow \phi_{%s}$\\\\\n" % (key, qNums)
s += "\hline\n"
s += "$%s$ & $%s$\\\\\n" % (phi, latex(self.orbitals[key]/genericFactor))
s += "\hline\n"
for i in range(self.dim):
s+= "$%s\cdot \\nabla %s$ & $%s$\\\\\n" % \
(xi[i], phi, latex(self.gradients[key][i]/genericFactor))
s += "\hline\n"
s += "$\\nabla^2 %s$ & $%s$\\\\\n" % (phi, latex(self.Laplacians[key]/genericFactor))
s += self.endTable(caption="Orbital expressions %s : %s. Factor $%s$ is omitted." % \
(self.__class__.__name__, qNums, latex(genericFactor)))
if (key+1)%self.figsPrPage == 0:
s += "\\clearpage\n"
return s
示例10: print_latex
def print_latex():
# 0- Raizes; 1- Forma Natural da respsota; 2- Resposta Natural;
# 3- Resposta Particular; 4- Resposta Transitoria; 5- Respsota Forcada
# 6- Resposta Completa
# 7-Sinal de entrada x(t)
##Perfumaria
dif = 0.9 -0.75
xdif = -0.15
font = {'family' : 'Arial',
'weight' : 'normal',
'size' : 18}
plt.rc('font', **font)
#plt.rc('text', usetex=True)
##Obtendo as respostas em Latex
RespostasEmLatex = [0]*(len(Respostas))
#print len(RespostasEmLatex)
for i in range(len(Respostas)):RespostasEmLatex[i] = '$'+str(latex(Respostas[i])) +'$'
## Tratamento Inicial para as raizes:
#replace(a, old, new[, count])
#r'$\left( \begin{array}{ll} 2 & 3 \\ 4 & 5 \end{array} \right)$'
#$\begin{bmatrix}-1.5, & 1.0\end{bmatrix}$
#\begin{Bmatrix} x & y \\ z & v \end{Bmatrix}
#print RespostasEmLatex[0]
#RespostasEmLatex[0]= RespostasEmLatex[0].replace("bmatrix","Bmatrix")
#RespostasEmLatex[0]= RespostasEmLatex[0].replace("}$","})$",1)
#print RespostasEmLatex[0]
####
#print RespostasEmLatex
xTLatex = '$' + latex(xT) +'$'
###Preparando para imprimir
log_figure = plt.figure("Representacao",facecolor='white')
ax1 = plt.axes(frameon = False)
ax1.get_xaxis().tick_bottom()
ax1.get_xaxis().set_visible(False)
ax1.axes.get_yaxis().set_visible(False)
for i in range(0,7,1):plt.axhline(dif*i,xmin = -5,xmax = 5, color = 'black',lw =1.5, linestyle = ':')
#log_figure.figure("Forma_Representativa:")
plt.title('')
#print RespostasEmLatex[0]
#plt.text(xdif,0.05,'Raizes:'+str(Respostas[0]))
plt.text(xdif,0.9,'Forma Natural:'+ur''+RespostasEmLatex[1])
plt.text(xdif,0.9-dif,'yn(t) = '+ur''+RespostasEmLatex[2])
plt.text(xdif,0.9-2*dif,'ypar(t) = '+ur''+RespostasEmLatex[3])
plt.text(xdif,0.9-3*dif,'ytran(t) = '+ur''+RespostasEmLatex[4])
plt.text(xdif,0.9-4*dif,'yfor(t) = '+ur''+RespostasEmLatex[5])
plt.text(xdif,0.9-5*dif,'yc(t) = '+ur''+RespostasEmLatex[6])
plt.text(xdif,0.9-6*dif,'x(t) = '+ur''+xTLatex)
log_figure.show()
示例11: visit_Call
def visit_Call(self, node):
buffer = []
fname = node.func.id
# Only apply to lowercase names (i.e. functions, not classes)
if fname in self.__class__.EXCEPTIONS:
node.func.id = self.__class__.EXCEPTIONS[fname].__name__
self.latex = sympy.latex(self.evaluator.eval_node(node))
else:
result = self.format(fname, node)
if result:
self.latex = result
elif fname[0].islower() and fname not in OTHER_SYMPY_FUNCTIONS:
buffer.append("\\mathrm{%s}" % fname.replace('_', '\\_'))
buffer.append('(')
latexes = []
for arg in node.args:
if isinstance(arg, ast.Call) and arg.func.id[0].lower() == arg.func.id[0]:
latexes.append(self.visit_Call(arg))
else:
latexes.append(sympy.latex(self.evaluator.eval_node(arg)))
buffer.append(', '.join(latexes))
buffer.append(')')
self.latex = ''.join(buffer)
else:
self.latex = sympy.latex(self.evaluator.eval_node(node))
return self.latex
示例12: solution_statement
def solution_statement(self):
lines = solutions.Lines()
derivative = self._qp['equation'].diff()
lines += r'''$y = {equation}, y' = {derivative}$'''.format(
equation=sympy.latex(self._qp['equation']),
derivative=sympy.latex(derivative)
)
original_y_coordinate = self._qp['equation'].subs({x: self._qp['location']})
lines += r'$y({original_x_coordinate}) = {original_y_coordinate}$'.format(
original_x_coordinate=self._qp['location'],
original_y_coordinate=original_y_coordinate
)
derivative_at_original_location = derivative.subs({x: self._qp['location']})
lines += r'''$y'({original_x_coordinate}) = {derivative_at_original_location}$'''.format(
original_x_coordinate=self._qp['location'],
derivative_at_original_location=sympy.latex(derivative_at_original_location)
)
unevaluated_approximation_of_answer = noevals.noevalAdd(original_y_coordinate, noevals.noevalMul(self._qp['delta'], derivative_at_original_location))
answer = original_y_coordinate + self._qp['delta'] * derivative_at_original_location
lines += r'$\therefore y({new_x_coordinate}) \approx {unevaluated_approximation_of_answer} = {answer}$'.format(
new_x_coordinate=self._qp['new_location'],
unevaluated_approximation_of_answer=noevals.latex(unevaluated_approximation_of_answer),
answer=sympy.latex(answer)
)
return lines.write()
示例13: simplex_table_to_tex_solution_only
def simplex_table_to_tex_solution_only(table):
solution = ''
var, target = table.solution
for i in range(table.amount_of_vars):
solution += "$x_{" + "{0:<2}".format(i) + "} = " + latex(var[i]) + '$\\\\'
solution += '$\Psi = ' + latex(target) + '$'
return solution
示例14: formula
def formula(self, quantity, adjust=True):
""" returns error formula of quantity as latex code
Args:
quantity: name of quantity or Quantity object
adjust: if True, replaces "_err" suffix by "\sigma" function and adds equals sign in front
Return:
latex code string of error formula
"""
quantity = quantities.parse_expr(quantity, self.data)
assert isinstance(quantity, quantities.Quantity)
if quantity.error_formula is None:
raise ValueError("quantity '%s' doesn't have an error formula.")
formula = quantity.error_formula
if isinstance(formula,str):
return formula
else:
# replace "_err" by sigma function
if adjust:
sigma = Function("\sigma")
for var in formula.free_symbols:
if var.name[-4:] == "_err":
formula = formula.subs(var, sigma( Symbol(var.name[:-4], **var._assumptions)))
return latex(sigma(quantity)) + " = " + latex(formula)
return formula
示例15: simplex_table_to_tex_table_only
def simplex_table_to_tex_table_only(table):
ret = """\\begin{tabular}{|c|"""
ret += ("c|"*(table.amount_of_vars + 1))
ret += "} \\hline"
ret += " & \\T \\B $ "
for j in range(table.amount_of_vars):
ret += "$&$"
ret += "x_{"+"{0:<2}".format(j) +"}"
ret += "$\\\\ \\hline "
for i in range(table.amount_of_equations):
ret += "$x_{" + "{0:<2}".format(table.basis[i]) + "}$"
ret += "& \\T \\B $ "
ret += latex(table.free[i])
for j in range(table.amount_of_vars):
ret += "$&$"
ret += latex(table.limits[i][j])
ret += "$\\\\ \\hline "
ret += "$\Psi$ & $"
ret += latex(table.target_free)
for j in range(table.amount_of_vars):
ret += "$&\\T \\B$"
ret += latex(table.target[j])
ret += "$\\\\ \\hline "
ret += """\\end{tabular}"""
return ret