Skip to content Skip to sidebar Skip to footer

How To Determine The Arrangement Of The Polynomial When Displaying It With Latex?

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

Solution 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

Solution 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 < 0else"+"+latex(b)), \
    ('+ c', latex(c) if c < 0else"+"+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

Post a Comment for "How To Determine The Arrangement Of The Polynomial When Displaying It With Latex?"