1

I do some calculations in my LaTeX document with sage. I want to include the results and do some comparisons. But to do that with \ifthenelse command, I need the value which is saved in the sage file. How can I get the result or is there another way to compare values from sagetex with an ifthenelse command?

\documentclass{article}
 \usepackage{sagetex}
 \usepackage{ifthen}
 \begin{document}
\begin{sagesilent}
  var('x')
   f = x^2
 \end{sagesilent}
$\ifthenelse{\sage{f(2)}>0}{a}{b}$

 \end{document}
2

A lot of packages don't "play well" with the sagetex package. This appears to be one such package in that it prevents you from typing things in the natural way you tried in your code. One approach is to take advantage of sagetex and Python to avoid even having to use the ifthen package. But if you want to use that package then you can have sagetex insert the command as a string. This solution doesn't seem particularly natural but I don't know of a better way.

\documentclass{article}
\usepackage{sagetex}
\usepackage{ifthen}
\begin{document}
\begin{sagesilent}
var('x')
f = x^2

output = r""
if f(2)>0:
    output += "a"
else:
    output += "b"

output1 = r"\ifthenelse{%s>%s}{a}{b}"%(f(2),0)
\end{sagesilent}
One way to handle the problem is to process it with sagetex to get\\
\sagestr{output}\\
and another way is to insert the command as a string\\
\sagestr{output1}
\end{document}

The result of running the code in Sagemath Cloud is: enter image description here

  • ok. Looks good. Thanks. Just to understand your code: You define the variable output as empty with output = r"" ,right? And the r stands what for? And i also don't understand the expression %s>%s. – typ42 Sep 16 '15 at 22:45
  • The r is for "raw" string. LaTeX has lots of characters such as \ that cause a problem if inserted in a string without the r before it. See here, for example. The %s indicates data is to be put there in the form of a string. %f is float, and %d for decimal. Less common alternative are given here. Your conditional was f(2)>0. Those two values are given at the end of the string. The first value, f(2) gets substituted in for %s and the second value, 0, is substituted for the second %s. – DJP Sep 17 '15 at 0:23
  • 1
    DJP's solution is the most natural one for sagetex: do the logic at the Sage/Python level. The \sage macro pulls in its value using LaTeX's \label and \ref mechanism, so if you do really want to use ifthenelse, you'd have to figure out how to "dereference" the \ref, which I think is possible but requires TeX wizardry that I don't understand. The corresponding Python "wizardry" isn't wizardry at all. :) – Dan Drake Sep 17 '15 at 0:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.