I'm trying to draw something like an inner box integral approximation but with dynamic upper bound, lower bound, and stepsize. Unfortunately the \foreach command of tikz is not cooperating.


\newcommand\firststep{{(\Abound + \stepsize)}}


    % works fine!!
    \foreach \y in {-2.25,-1.75,...,2.5} {
        \draw (0, \y) -- ++(1,0);

    % works fine!!
    \foreach \y in {\Abound, -1.75,...,\Bbound}{
        \draw (0,\y) --++ (-1,0);

    % gives error (Argument of \pgffor@@dotscharcheck has an extra }. [        }])
    % \foreach \y in {\Abound,\firststep,...,\Bbound}{
    %     \draw (0,\y) --++ (-1,0);
    % }

    % gives error (Paragraph ended before \pgfmath@dimen@@ was complete. [])
    % \foreach \y in {\Abound, \number\numexpr\Abound + 0.5\relax,...,\Bbound}{
    %     \draw (0,\y) --++ (-1,0);
    % }

    % gives less useful error
    % \foreach \y in {\the\numexpr\Abound, \the\numexpr\firststep,...,\the\numexpr\Bbound}{
    %     \draw (0,\y) --++ (-1,0);
    % }


In the first \foreach I set the bounds and stepsize manually, and it worked fine. The second attempt I use the defined upper and lower limits, but still set the stepsize manually; this also worked. The third through fifth I tried all the things I've found here on TeX.SE to address this particular issue. None of them worked.

Does anybody have any advice on how to get these dynamic bounds and step size working?

A broader question is how does TikZ/PGF/LaTeX handle computation? I've seen math enclosed in round parentheses, in brackets, and behind more TeXish commands. What is the deal?

  • 5
    \numexpr only works with integers! \foreach does not evaluate the contents when looping, so it sees in {-2.25, (-2.25 + 0.5), ..., 2.25} where it cannot match the ... correctly (until right after, \foreach sees only text). You will need to evaluate \firststep before it enters \foreach. \pgfmathsetmacro\firststep{…} would be the PGF-way to do this. — Related: Q36713, Q110962, Q142188, Q244753. – Qrrbrbirlbel Jun 19 '15 at 21:11
  • @Qrrbrbirlbel Would you like to answer, or is one of those questions a duplicate (I'm lazy, so I haven't looked at them)? – Torbjørn T. Jun 20 '15 at 12:05
  • Dag, I never intended to ask a duplicate. I searched before posting the question, but I didn't find that question. Thanks for sharing! – Paul Stiverson Jun 20 '15 at 14:26

Browse other questions tagged or ask your own question.