# How to calculate the variable in foreach with ifnum?

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
\else
\relax
\fi
}
}
\end{tikzpicture}
\end{docume


The code above can't be compiled successfully.

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

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

\documentclass{article}

\usepackage{tikz}

\begin{document}

\begin{tikzpicture}
\foreach\x in{1,...,10}{
\foreach\y in{1,...,10}{
\ifnum\numexpr\x-\y>1
\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
%...

• 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. May 21, 2017 at 4:20
• @Ice0cean: See the appendage to my answer.
– Werner
May 21, 2017 at 5:22
• Also \foreach\y[evaluate={\z=int(\x-\y);}] in{1,...,10}{\ifnum\z>1\relax... 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. May 21, 2017 at 7:32