5

I want to draw some points on a grid with the condition x-y>1, and I write the following code:

\documentclass[tikz]{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
  \foreach\x in{1,...,10}{
    \foreach\y in{1,...,10}{
    \ifnum \x-\y>1
        \shade[ball color=red] (\x,\y) circle (0.2cm);
    \else
        \relax
    \fi
    }
  }
\end{tikzpicture}
\end{docume

The code above can't be compiled successfully.

2
  • You could also use ifthen package.
    – CarLaTeX
    May 21, 2017 at 4:20
  • You don't need an else branch if you don't do anything. \if...\fi would suffice.
    – percusse
    May 21, 2017 at 7:32

1 Answer 1

9

You need to evaluate the numeric calculation (\numexpr) before testing it as a condition (\ifnum).

enter image description here

\documentclass{article}

\usepackage{tikz}

\begin{document}

\begin{tikzpicture}
  \foreach\x in{1,...,10}{
    \foreach\y in{1,...,10}{
    \ifnum\numexpr\x-\y>1
      \shade[ball color=red] (\x,\y) circle (0.2cm);
    \fi
    }
  }
\end{tikzpicture}

\end{document}

The token > stops the evaluation of \numexpr\x-\y, leaving the evaluated result in the input stream for conditioning against 1.


For more complex evaluations, use \fpeval (from xfp/LaTeX3):

%...
\usepackage{xfp}
% ...
\ifnum\fpeval{\x^2+\y^2}<10
% or
\ifnum\fpeval{abs(\x-\y)}<3
%...
4
  • Thanks for your answer :-). Can I make some other math calculation in ifnum? for example the condition is x^2+y^2<10 or abs(x-y)<3.
    – Ice0cean
    May 21, 2017 at 4:20
  • @Ice0cean: See the appendage to my answer.
    – Werner
    May 21, 2017 at 5:22
  • 1
    Also \foreach\y[evaluate={\z=int(\x-\y);}] in{1,...,10}{\ifnum\z>1\relax...
    – percusse
    May 21, 2017 at 7:31
  • For the floating-point case, you might want to add a round() (or similar) function to give an integer answer.
    – Joseph Wright
    May 21, 2017 at 7:32

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.