如何将\ n传播到sympy.latex() [英] How to propagate `\n` to sympy.latex()
问题描述
目标是将具有6个以上参数的多项式格式化为绘图标题.这是我的字符串表达式函数的多项式参数,灵感来自此答案,然后是 sym.latex()
:
The Goal is to format a polynomial with more than 6 parameters into a plot title.
Here is my polynomial parameter to string expression function, inspired by this answer, followed by sym.latex()
:
def func(p_list):
str_expr = ""
for i in range(len(p_list)-1,-1,-1):
if (i%2 == 0 and i !=len(p_list)):
str_expr =str_expr + " \n "
if p_list[i]>0:
sign = " +"
else:
sign = ""
if i > 1:
str_expr = str_expr+" + %s*x**%s"%(p_list[i],i)
if i == 1:
str_expr = str_expr+" + %s*x"%(p_list[i])
if i == 0:
str_expr = str_expr+sign+" %s"%(p_list[i])
print("str_expr",str_expr)
return sym.sympify(str_expr)
popt = [-2,1,1] # some toy data
tex = sym.latex(func(popt))
print("tex",tex)
输出:
str_expr
+ -1*x**2 + 1*x
-2
tex - x^{2} + x - 2
在 str_expr
中的
可见从 \ n
的换行符,但是在 sympy.latex
输出中,该换行符消失了.
in str_expr
the line breaks from \n
are visible, yet in the sympy.latex
output the are gone.
如何传播此换行符?
我使用@ wsdookadr答案并对其进行了修改,以便plt.title将函数的结果作为文本作为参数
I took @ wsdookadr answer and modified it, so that plt.title takes the result of the function as text the argument
def tex_multiline_poly(e, chunk_size=2, separator="\n"):
tex = ""
# split into monomials
print("reversed(e.args)",reversed(e.args))
mono = list(e.args)
print("mono",mono)
mono.reverse()
print("mono",mono)
# we're going split the list of monomials into chunks of chunk_size
# serialize each chunk, and insert separators between the chunks
for i in range(0,len(mono),chunk_size):
chunk = mono[i:i + chunk_size]
print("sum(chunk)",sum(chunk))
print("sym.latex(sum(chunk))",sym.latex(sum(chunk)))
if i == 0:
tex += r'$f(x)= %s$'%(sym.latex(sum(chunk)))+separator
else:
tex += '$%s$'%(sym.latex(sum(chunk))) + separator
return tex
popt = est.params
x = sym.symbols('x')
p = sym.Poly.from_list(reversed(popt),gens=x)
tex = tex_multiline_poly(p.as_expr(),chunk_size=2)
plt.title(text=tex)
推荐答案
在您的代码中,您将为除最后一个之外的所有偶数幂单项式插入换行符.
In your code, you're inserting a linebreak for every even-power monomial, except for the last one.
if (i%2 == 0 and i !=len(p_list)):
str_expr =str_expr + " \n "
由于您只是从系数列表中构建多项式,因此可以简化代码.
Since you are just building a polynomial from a list of coefficients, your code can be simplified.
通常,我们想要的是象征性地构建/转换/处理事物,最后只对它们进行序列化并以某种特定格式打印结果
Generally what we want is to build/transform/handle things symbolically, and only at the end serialize them and print the result in some specific format
import sympy as sym
x = sym.symbols('x')
def func(p_list):
expr = 0
for i in range(len(p_list)-1,-1,-1):
expr += p_list[i] * (x ** i)
return sym.sympify(expr)
popt = [-2,1,1]
p = func(popt)
p_tex = sym.latex(p)
p_str = str(p)
print("str:", p_str)
print("tex:", p_tex)
输出:
str: x**2 + x - 2
tex: x^{2} + x - 2
我们可以通过使用SymPy的内置函数从系数列表中构建 poly来进一步简化此操作:
We could simplify this even further by using SymPy's built-in functions to build the poly from a list of coefficients:
import sympy as sym
from sympy import symbols
popt = [-2,1,1]
x = symbols('x')
p = sym.Poly.from_list(reversed(popt),gens=x)
p_tex = sym.latex(p.as_expr())
p_str = str(p.as_expr())
print("str:", p_str)
print("tex:", p_tex)
输出:
str: x**2 + x - 2
tex: x^{2} + x - 2
输出看起来是否像您期望的那样?
Does the output look like what you would expect?
更新:
在详细了解了用例之后,这是一个版本,该版本以表达式的乳胶形式在每N = 2个单项式中插入分隔符.
After learning more about the use-case, here's a version that inserts separators every N=2 monomials in the latex form of your expression.
import sympy as sym
from sympy import symbols
popt = [-2,1,1]
x = symbols('x')
p = sym.Poly.from_list(reversed(popt),gens=x)
def tex_multiline_poly(e, chunk_size=2, separator="\n"):
tex = ""
# split into monomials
mono = list(reversed(e.args))
# we're going split the list of monomials into chunks of chunk_size
# serialize each chunk, and insert separators between the chunks
for i in range(0,len(mono),chunk_size):
chunk = mono[i:i + chunk_size]
tex += sym.latex(sum(chunk)) + separator
return tex
p_tex = tex_multiline_poly(p.as_expr(),chunk_size=2)
p_str = str(p.as_expr())
print("str:",p_str)
print("tex:",p_tex)
输出:
str: x**2 + x - 2
tex: x^{2} + x
-2
错误的编辑
这篇关于如何将\ n传播到sympy.latex()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!