3

As part of a drawing that will go with an explanation of diffraction, I want to draw the "outer rays" of a beam of light and draw several rays in between. An MWE of how I'm going about this is shown below:

\documentclass{standalone}
\usepackage{pgfplots,tikz}
\usetikzlibrary{calc}
\pgfplotsset{compat=newest}
\begin{document}
\begin{tikzpicture}[scale=1]
    \draw[black,semithick] (-3,1) -- (0,1);
    \draw[black,semithick] (-3,-1) -- (0,-1);
    \def \n {10}
    \foreach \s in {1,...\n-1}
    {
        \draw[lightgray,semithick] ($(-3,1)!\s/\n!(-3,-1)$) -- ($(0,1)!\s/\n!(0,-1)$);
    }
\end{tikzpicture}
\end{document}

This gives me the following error:

Runaway argument?
\pgffor@stop \pgffor@@stop \expandafter \pgffor@dots@charcheck \pgffor@dotsvalue \ETC.
! File ended while scanning use of \pgffor@dots@stripcontext.

The pgffor@dots stuff makes me suspect the problem might lie in the range specification for \s but as far as I can tell there's nothing wrong with it. Can anyone enlighten me?

Wouter
  • 541

1 Answers1

3

You are missing , in {1,...\n-1} which should be {1,...,\n-1} Note the , after .... Further I have defined \n-1 as a macro and taken it outside the loop (this can be done with the facilities of \foreach too though).

\documentclass{standalone}
\usepackage{pgfplots,tikz}
\usetikzlibrary{calc}
\pgfplotsset{compat=newest}
\begin{document}
\begin{tikzpicture}[scale=1]
    \draw[black,semithick] (-3,1) -- (0,1);
    \draw[black,semithick] (-3,-1) -- (0,-1);
    \def \n {10}
    \pgfmathsetmacro{\tmp}{\n-1}
    \foreach \s in {1,...,\tmp}
    {
        \draw[lightgray,semithick] ($(-3,1)!\s/\n!(-3,-1)$) -- ($(0,1)!\s/\n!(0,-1)$);
    }
\end{tikzpicture}
\end{document}

enter image description here

  • Thanks! I should have noticed that missing , though :P However, I would like some expansion on the \n-1. I assume it doesn't work because the -1 is interpreted as a unit and not as part of an arithmetic expression. Can I do arithmetics in the range definition of a foreach loop? – Wouter May 13 '15 at 14:23
  • @Wouter: percusse already told: \number\numexpr\n-1. I would go with \pgfmathsetmacro way as in my answer. –  May 13 '15 at 14:24
  • Ah yes, I see percusse edited their comment. Thanks again. – Wouter May 13 '15 at 14:26
  • It might be appropriate to use \pgfmathtruncatemacro (it doesn't matter in this example, though). – Qrrbrbirlbel May 13 '15 at 14:38