ifthenelse inside TikZ: not working
An alternative approach would be the standard \ifnum
construct combined with \pgfmathparse
. Note that since 1.6 is a float, you must provide a tolerance. A simple \pgfmathparse{\y == 1.6 ? int(1) : int(0)}
would not work.
Here is the complete solution:
\documentclass[border=0.2cm]{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\foreach \y in {0,0.2,0.4,...,1.6}{
\pgfmathparse{abs(\y - 1.6) < 0.001 ? int(1) : int(0)}
\ifnum\pgfmathresult=1
\draw [thin,-latex] (-0.8,\y) -- (-0.3,\y) node [above,midway] {U};
\else
\draw [thin,-latex] (-0.8,\y) -- (-0.3,\y);
\fi
}
\end{tikzpicture}
\end{document}
You can surely use \ifthenelse
, but
- the test compares only integer
- it uses a single
=
- when TikZ comes to 1.6 it actually sees it as 1.59998
Use integers, then:
\documentclass[border=0.2cm]{standalone}
\usepackage{tikz}
\usepackage{ifthen}
\begin{document}
\begin{tikzpicture}
\foreach \y in {0,2,4,...,16}{
\ifthenelse{\y = 16}
{\draw [thin,-latex] (-0.8,1.6) -- (-0.3,1.6) node [above,midway] {U}}
{\draw [thin,-latex] (-0.8,\y/10) -- (-0.3,\y/10)}
;
}
\end{tikzpicture}
\end{document}
The mandatory xintexpr
solution. This time I spare you folks the \xintFor
, as \foreach
is too venerable.
I don't know how to tell \foreach
to expand its list argument first, hence I have to resort to the device from the TikZ
manual with a \mylist
definition first.
The method here is for more complicated situation where fixed point operations must be exact.
\documentclass[border=0.2cm]{standalone}
\usepackage{tikz}
\usepackage{xintexpr}
\begin{document}
\begin{tikzpicture}
\edef\mylist{\xinttheiexpr [1] 0..[+0.2]..1.6\relax}%
% (The [1] is to tell it to use fixed point notation
% with one digit after decimal mark, and this expands to
% 0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6 )
%
\foreach \y in \mylist
{%
\xintifboolexpr{\y = 1.6}
{\draw [thin,-latex] (-0.8,1.6) -- (-0.3,1.6) node [above,midway] {U}}
{\draw [thin,-latex] (-0.8,\y) -- (-0.3,\y)}
;
}
\end{tikzpicture}
\end{document}