0

The TikZ user guide (version 3.18b, page 1042) says this:

ifthenelse(x,y,z) This returns y if x evaluates to some non-zero value, otherwise z is returned.

It would appear that both y and z are first evaluated and then returned, which is (to me) a surprise; a TeX \if does not evaluate the unused option -- so why does TikZ bother to evaluate an unused option? I discovered this in a vain attempt to avoid division by zero:

\documentclass{article}

\usepackage{tikz}

\begin{document}

\pgfmathsetmacro{\foo}{0}

\pgfmathsetmacro{\foobar}{ifthenelse(equal(\foo,0),0,1)}\foobar

%% Both return the error: "You've asked me to divide 1' by0'..." % Uncomment the following to see the problem: %\pgfmathsetmacro{\foobar}{ifthenelse(equal(\foo,0),0,1/\foo)}\foobar %\pgfmathsetmacro{\foobar}{ifthenelse(greater(\foo,0),1/\foo,0)}\foobar

\end{document}

There are a number of non-TikZ approaches (for the moment I have settled on \ifdim\foo pt=0...\else...\fi). Just wondering what a more TikZ-idiomatic approach might be.

sgmoye
  • 8,586
  • It works perfectly here. Probably something is wrong elsewhere. –  Feb 06 '21 at 14:41
  • Did you uncomment the second two instances of \pgfmathsetmacro{\foo}...? They do not work. – sgmoye Feb 06 '21 at 15:18
  • Yes, both work in latest PGF (TeX Live 2020). It's 1.0 in both –  Feb 06 '21 at 15:20
  • By bad. The problem occurs with \pgfmathsetmacro{\foo}{0} -- I posted, in error, an interim version of the file. Changed in code. Apologies. And, yes, using MacTeX2020. – sgmoye Feb 06 '21 at 15:24
  • 1
    As I just checked in the code, the question/answer from 2015 still applies. It is simply the way the expression evaluator of pgf works. ifthenelse is a function with three arguments, and pgf evaluates the arguments first before applying the function to the values. – gernot Feb 06 '21 at 15:28
  • I did search existing questions and did not find that 2015 answer. Thanks. Looks like that's just the way it is. – sgmoye Feb 06 '21 at 15:32
  • @gernot I did try that, but if \foo happens to be a non-integer, then \ifnum gives an error: Missing number, treated as zero. – sgmoye Feb 06 '21 at 15:37
  • @gernot Yes, as I pointed out in my question, I use the (seems kludgy to me) \ifdim\foo pt=0...\else...\fi trick – sgmoye Feb 06 '21 at 15:49
  • Ah, sorry. It seems you have already found the best solution ... – gernot Feb 06 '21 at 15:50

1 Answers1

1

Don't poke the dancing bear.

\documentclass{article}

\usepackage{tikz}

\begin{document}

\pgfmathsetmacro{\foo}{0}

\pgfmathsetmacro{\foobar}{ifthenelse(equal(\foo,0),0,1/ifthenelse(equal(\foo,0),1,\foo))}\foobar

\end{document}

John Kormylo
  • 79,712
  • 3
  • 50
  • 120