Sympy - fraction manipulation

怎甘沉沦 提交于 2019-12-23 17:14:11

问题


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 .

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

回答1:


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)


来源:https://stackoverflow.com/questions/33619937/sympy-fraction-manipulation

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