7

I have a problem drawing a chord network with TikZ.

This is my code so far:

\begin{tikzpicture}
    \xdef\N{16}
    \xdef\deltadegree{360/\N}
    \draw[thick] (0,0) circle (6);

    \foreach \i in {0,...,15} {
        % predecessor
        \pgfmathparse{mod(\i-1,\N)}
        \draw[color=red] (-\i*\deltadegree+90:6) -- (-1*\pgfmathresult*\deltadegree+90:6);


        % successor
        \pgfmathparse{mod(\i+1,\N)}
            \draw (-\i*\deltadegree+90:6) -- (-1*\pgfmathresult*\deltadegree+90:6);

        % fingers
        \foreach \j in {0,...,4}{
            \pgfmathparse{mod(\i+2^\j,\N)}
            \draw (-\i*\deltadegree+90:6) -- (-1*\pgfmathresult*\deltadegree+90:6);
        }
    }

    \foreach \i in {0,...,15}
        \node[circle,fill=white,draw=black,thick] at (-\i*\deltadegree+90:6) {\i};
\end{tikzpicture}

The problem with this code is, TikZ only draws lines from node 6 to every other node, but i thought it iterates over all nodes, calulates the destination for each finger, and draws that line.

What am I doing wrong?

8

The \pgfmathresult macro gets overwritten very quickly by TikZ. You should always assign the results to a different macro immediately, which you can do using the \pgfmathsetmacro{<macro name>}{<math expression>} command (see also this question).

Here's your code with the adaptation. Note that the lines from the "successor" loops just draw over the "predecessor" loops.

\documentclass{article}

\usepackage{tikz}
\begin{document}

\begin{tikzpicture}
    \xdef\N{16}
    \xdef\deltadegree{360/\N}
    \draw[thick] (0,0) circle (6);

    \foreach \i in {0,...,15} {
        % predecessor
        \pgfmathsetmacro{\result}{mod(\i-1,\N)}
        \draw[color=red] (-\i*\deltadegree+90:6) -- (-1*\result*\deltadegree+90:6);


        % successor
        \pgfmathsetmacro{\result}{mod(\i+1,\N)}
            \draw (-\i*\deltadegree+90:6) -- (-1*\result*\deltadegree+90:6);

        % fingers
        \foreach \j in {0,...,4}{
            \pgfmathsetmacro{\result}{mod(\i+2^\j,\N)}
            \draw (-\i*\deltadegree+90:6) -- (-1*\result*\deltadegree+90:6);
        }
    }

    \foreach \i in {0,...,15}
        \node[circle,fill=white,draw=black,thick] at (-\i*\deltadegree+90:6) {\i};
\end{tikzpicture}

\end{document}
  • that worked. thank a lot for the explanation. – Zoran Zaric Feb 4 '11 at 16:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.