Consider having to compute some value using an operation that might not be defined for certain values, like e.g. the tangent function. To avoid raising exceptions, I tried using pgfmath's ifthenelse(<expression>, <true code>, <false code>)
, like in the following example:
\documentclass[tikz, border=2mm]{standalone}
\usepackage{xifthen}
\begin{document}
\begin{tikzpicture}
\foreach \D [count=\C] in {85,...,95}
{ \pgfmathsetmacro{\goodAngle}{ifthenelse(or(\D<=86, \D>=94), 1, 0)}
\pgfmathsetmacro{\Tan}{ifthenelse(\goodAngle == 1, tan(\D), 0)}
%\ifthenelse{\goodAngle = 1}
% { \pgfmathsetmacro{\Tan}{tan(\D)}}
% { \pgfmathsetmacro{\Tan}{0}}
\node[right] at (0,-\C*0.7) {\D$^{\circ}$, \goodAngle, \Tan};
}
\end{tikzpicture}
\end{document}
I expected this to only compute the tangent of the given angle if it was previousely determinded to be a good angle (it would have been sufficient to exclude just 90°, but here I excluded anles from 87° to 93°), but it appears to be evaluating both expressions which obviousely fails for 90°. The result is the same when doing it in "one step", that is without computing the \goodAngle
first, as well as using the shorthand notation for ifthenelse
(which is <expression> ? <true code> : <false code>
). To check that it's not my thinking that is flawed, I used the \ifthenelse
macro from the xifthen package, which, as expected, only evaluates the correct expression.
If one uncomments the three commented lines and comments out the line above like this
\begin{tikzpicture}
\foreach \D [count=\C] in {85,...,95}
{ \pgfmathsetmacro{\goodAngle}{ifthenelse(or(\D<=86, \D>=94), 1, 0)}
%\pgfmathsetmacro{\Tan}{ifthenelse(\goodAngle == 1, tan(\D), 0)}
\ifthenelse{\goodAngle = 1}
{ \pgfmathsetmacro{\Tan}{tan(\D)}}
{ \pgfmathsetmacro{\Tan}{0}}
\node[right] at (0,-\C*0.7) {\D$^{\circ}$, \goodAngle, \Tan};
}
\end{tikzpicture}
one obtains the expected result:
This behaviour is not limited to the tangent function, it also emerges for e.g. simple division by zero, like in
\begin{tikzpicture}
\foreach \D [count=\C] in {-5,...,5}
{ \pgfmathsetmacro{\goodValue}{ifthenelse(or(\D<=-2, \D>=2), 1, 0)}
\pgfmathsetmacro{\byZero}{ifthenelse(\goodValue == 1, 1/\D, -1)}
%\ifthenelse{\goodValue = 1}
% { \pgfmathsetmacro{\byZero}{1/\D}}
% { \pgfmathsetmacro{\byZero}{-1}}
\node[right] at (0,-\C*0.7) {\D, \goodValue, \byZero};
}
\end{tikzpicture}
Is this expected behaviour (I doubt it), or is this a bug? Are there facilities in pgfmath who work like a try ... except
statement, or even better, a non-Pokémon exception approch that lets me catch specific error types, like a try ... except ErrorType1 ... except ErrorTypeN ... finally
construct? If not, does something like this exist at all in the world of TeX, and is it even possible?