0

Why this code produce some value not in the diagonal? Nine in total all below the diagonal.

\documentclass{article}
\usepackage{tikz}
\usepackage{ifthen}
\begin{document}

\begin{tikzpicture}
\clip[](.75,.75)rectangle(7.75,7.75);
\foreach \x in {1,...,7}
{
\foreach \y in {1,...,7}
{
%\pgfmathsetmacro{\rapporto}{\x/\y}
\pgfmathtruncatemacro{\rapporto}{\x/\y}
\ifthenelse
{1=\rapporto}
{\node[scale=1,red]at(\x,\y){$\x/\y$};}
{}
}
}
\end{tikzpicture}
\end{document}
Werner
  • 603,163
yngabl
  • 448

2 Answers2

3

It is because the \pgftruncatemacro will truncate your result, then some combinations of \x and \y will give 1. Use this:

\documentclass{article}
\usepackage{tikz}
\usepackage{ifthen}

\begin{document}

\begin{tikzpicture}
\clip[](.75,.75)rectangle(7.75,7.75);
\foreach \x in {1,...,7}
{
\foreach \y in {1,...,7}
{
\ifnum\x=\y
 \node[scale=1,red]at(\x,\y){$\x/\y$};
\else
 \relax
\fi
}
}
\end{tikzpicture}
\end{document}
1

To see why this is the case, output the entire (7 x 7) matrix of values \rapporto evaluates to:

enter image description here

\foreach \x in {1,...,7} {%
  \foreach \y in {1,...,7} {%
    \pgfmathtruncatemacro{\rapporto}{\x / \y}%
    \rapporto~%
  }%
  \par
}

You'll see that the diagonal evaluates to 1, but also other elements (since truncation of values slightly larger than 1 will result in 1). If you want to focus on the diagonal, rather consider the condition \x = \y. Moreover, there is no need for ifthen:

enter image description here

\documentclass{article}

\usepackage{tikz}

\begin{document}

\begin{tikzpicture}
  \clip (.75, .75) rectangle (7.75, 7.75);
  \foreach \x in {1,...,7} {%
    \foreach \y in {1,...,7} {%
      \ifx\x\y% \x == \y
        \node [red] at (\x, \y){$\x / \y$};
      \else% \x != y
        \node [black] at (\x, \y){$\x / \y$};
      \fi
    }
  }
\end{tikzpicture}

\end{document}
Werner
  • 603,163