Niek de Klein
Niek de Klein

Reputation: 8824

Keep expression exactly as written for latex conversion

I want to get the expression of p__s_alpha = 1/k * Product(a_0,(i,1,O)) in latex. I use:

print sympy.latex(p__s_alpha)

When I run latex on the result I get the following equation:

incorrect

However, I want to print this equation:

correct

Is there a way to keep the representation of the expression the way it is?

Upvotes: 2

Views: 146

Answers (1)

asmeurer
asmeurer

Reputation: 91500

I started writing up an answer about how you could make your own custom printer that does this, but this I realized that there's already an option in latex that does what you want, the long_frac_ratio option. If that ratio is small enough, any fraction that is small enough will be printed as 1/b*a instead of a/b.

In [31]: latex(p__s_alpha, long_frac_ratio=1)
Out[31]: '\\frac{1}{k} \\prod_{i=1}^{O} a_{0}'

If you're interested, here is some of what I was going to write about writing a custom printer:

Internally, SymPy makes no distinction between a/b and a*1/b. They are both represented by the exact same object (see http://docs.sympy.org/latest/tutorial/manipulation.html).

However, the printing system is different. As you can see from that page, a/b is represented as Mul(a, Pow(b, -1)), i.e., a*b**-1, but it is the printer that converts this into a fraction format (this holds for any printer, not just the LaTeX one).

The good news for you is that the printing system in SymPy is very extensible (and the other good news is that SymPy is BSD open source, so you can freely reuse the printing logic that is already there in extending it). To create a custom LaTeX printer that does what you want, you need to subclass LatexPrinter in sympy.printing.latex and override the _print_Mul function (because as noted above, a/b is a Mul). The logic in this function is not really split up modularly, so you'll really need to copy the whole source and change the relevant parts of it [as I noted above, for this one, there is already an option that does what you want, but in other cases, there may not be].

And a final note, if you make a modification that would probably be wanted be a wider audience, we would love to have you submit it as a pull request to SymPy.

Upvotes: 2

Related Questions