tom roddick
tom roddick

Reputation: 47

Sympy - fraction manipulation

I basically want Sympy to generate latex code

\frac{x-1}{3} = y   

but whenever I ask it generate the Tex component of things Sympy always returns

\frac{x}{3} - \frac{1}{3} 

How do I avoid splitting up the equations, and assign an equals operator to another variable.

I have not attempted to add the "y =" part to the code yet as I wanted to clarify the fraction situation first, but since I have had to come cap in hand to stack exchange I thought I would ask both questions. I have been through every tutorial page I could find but to no avail.

Any help would be much appreciated although I would ask you keep it relatively simple !!!

Thanks in advance .

from sympy import *
x = Symbol("x")
a = (x-Integer(1))
b = (3)
c = a/b
print(latex(c))

Upvotes: 4

Views: 582

Answers (2)

user2314737
user2314737

Reputation: 29437

Try with sympify:

c = sympify("(x-1)/3", evaluate=False)
print(latex(c))
# \frac{x - 1}{3}

To add the = y use an f-string:

print(f"{latex(c)} = {latex(y)}")
# \frac{x - 1}{3} = y

Upvotes: 0

aghitza
aghitza

Reputation: 176

The issue comes from sympy automatically expanding (x-1)/3 into x/3-1/3. So one solution is to ask sympy to factor this back:

In [18]: c = a/b; c
Out[18]: x/3 - 1/3

In [19]: d = c.factor(); d
Out[19]: (x - 1)/3

In [20]: print(latex(d))
\frac{1}{3} \left(x - 1\right)

Upvotes: 1

Related Questions