0

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:

enter image description here

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

JohanC
  • 71,591
  • 8
  • 33
  • 66
Gabi
  • 1

2 Answers2

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
smichr
  • 16,948
  • 2
  • 27
  • 34
0

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
JohanC
  • 71,591
  • 8
  • 33
  • 66