How to determine the arrangement of the polynomial when displaying it with latex?

二次信任 提交于 2019-12-25 01:49:45

问题


I am not sure if it is an issue with my python code or with the latex but it keeps rearranging my equation in the output.

Code:

ddx = '\\frac{{d}}{{dx}}'

f = (a * x ** m) + (b * x ** n) + d
df = sym.diff(f)

df_string = tools.polytex(df)
f_string = tools.polytex(f)

question_stem = f"Find $_\\displaystyle {ddx}\\left({f_string}\\right)$_"

output:

In this case a = 9, b = -4, c = 4, m = (-1/2), n = 3 and I want the output to be in the order of the variable f.

I have tried changing the order to 'lex' and that did not work nor did .expand() or mode = equation


回答1:


There is an order option for the StrPrinter. If you set the order to 'none' and then pass an unevaluated Add to _print_Add you can get the desired result.

>>> from sympy.abc import a,b,c,x,m,n
>>> from sympy import S
>>> oargs = Tuple(a * x ** m, b * x ** n,  c) # in desired order
>>> r = {a: 9, b: -4, c: 4, m: -S.Half, n: 3}
>>> add = Add(*oargs.subs(r).args, evaluate=False) # arg order unchanged
>>> StrPrinter({'order':'none'})._print_Add(add)
9/sqrt(x) - 4*x**3 + 4



回答2:


Probably this will not be possible in general, as SymPy expressions get reordered with every manipulation, and even with just converting the expression to the internal format.

Here is some code that might work for your specific situation:

from sympy import *
from functools import reduce

a, b, c, m, n, x = symbols("a b c m n x")

f = (a * x ** m) + (b * x ** n) + c

a = 9
b = -4
c = 4
m = -Integer(1)/2
n = 3

repls = ('a', latex(a)), ('+ b', latex(b) if b < 0 else "+"+latex(b)), \
    ('+ c', latex(c) if c < 0 else "+"+latex(c)), ('m', latex(m)), ('n', latex(n))
f_tex = reduce(lambda a, kv: a.replace(*kv), repls, latex(f))

# only now the values of the variables are filled into f, to be used in further manipulations
f = (a * x ** m) + (b * x ** n) + c 

which leaves the following in f_tex:

9 x^{- \frac{1}{2}} -4 x^{3} 4


来源:https://stackoverflow.com/questions/58533081/how-to-determine-the-arrangement-of-the-polynomial-when-displaying-it-with-latex

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!