Is there a way to specify that `\sqrt{}`s should be avoided in favor of exponents when using the `latex()` function?
Background: I'm using Sage to do some computations for a LaTeX document I'm preparing. My preferred approach is to include the script directly in the markup, using SageTeX to parse the code and print the results in TeX-readable form. The computations relevant to this question result in a longish list of numbers, most of which are of the form something*sqrt(pi)
. My intention is to include this list in a table, which I'm constructing using a little Python script I wrote. The script takes a lists of TeX-formatted strings and returns a string with the markup for a table with those strings as rows.
The problem: When I call the latex()
function on the list elements to prepare them for serialization into the table, I get results like this: \frac{3}{7} \sqrt{7} \sqrt{\pi}
. This is not at all how I would type this if I were "TeXifying" it myself---I'd much prefer \frac{3}{7} \sqrt{7 \pi}
. Even \frac{3}{7} (7 \pi)^{1/2}
would be preferable IMO.
Obviously, I could just generate a table and then copy-paste it into my document, tweaking where necessary. I could also try writing a little Python function to massage the output into the desired form. But it made me wonder if there is any way to control or customize the output of latex()
beyond the basic delimiter-setting functions I found in the docs, and I think that'd be worthwhile to know in any event.
Specific question: Is there a way to "tell" Sage to avoid using \sqrt{}
in its LaTeX output in favor of fractional exponents?
Welcome to Ask Sage! Thank you for your question!
As far as I can tell,
Sage
doesn't allow to "prettify" expression at the math level. For exemple, it insists to replace radicals in a denominator by radicals in the numerator divided by their squares in the denominator (i. e. replaces $\displaystyle\frac{1}{\sqrt{x}}$ by $\displaystyle\frac{\sqrt{x}}{x}$). The usual argument for that behaviour is that there is no algorithmic definition of a "pretty" expression...It can even be asinine in the extreme :
You could probably do that by substituting regexes of the latex form, but this is probably highly non-trivial...
Thanks, Emmanuel---this is what I feared. I imagine writing a fully satisfactory solution to this problem that worked on all types of expressions, even one limited to just my personal stylistic preferences, would be a daunting task indeed, and almost certainly not worth the effort when copy-pasting is always an option. Fortunately for me, @dsejas has taken the time to write up a very nice and reasonably short home-baked solution to this problem that works for the use-cases I mentioned.