[Tex/LaTex] A simple if-then statement in tikz

random numberstikz-pgf

I have been trying to generate a graph where two vertices are connected with probability p. Here is what I tried so far,

\pgfmathsetseed{\number\pdfrandomseed}
\begin{tikzpicture}
 % size of circle
 \def \radius {2cm}
 \def \margin {8}
 % number of vertices
 \def \n {5}
 % Probability for an edge to show up between vertices
 \def \p {0.5}

 % Drawing the vertices/nodes
 \foreach \s in {1,...,\n}
  \node[draw, circle] (\s) at ({360/\n * (\s - 1)}:\radius) {};

 % Drawing the edges
 \foreach \s in {1,...,\n}
  \foreach \t in {\s,...,\n}
    % Generate and store a random number to the variable \dummynum
    \pgfmathparse{rnd}
    \pgfmathsetmacro{\dummynum}{\pgfmathresult}
    % If dummynum is less than p, edge is drawn; otherwise nothing happens
    \ifthenelse{\lengthtest{\dummynum pt < \p pt}}{\draw (\t) -- (\s);}{}
\end{tikzpicture}

The compiler has been unsuccessful in compiling it, giving me an error "Paragraph ended before \pgffor@next was complete".

I am sure that the problem is in the ifthenelse line, but so far I have no clue how to fix it. Can anyone point out the error and how to fix it? Thanks.

Best Answer

Rather than deal with the \ifthenelse macro from the xifthen package, I prefer to use \ifdim ...\fi (which the tikz parser recognizes). There is also the \pgfmathifthenelse, but that would require using "..." which my editor automatically converts to ``...'' (one of its less useful features). Also, \foreach requires the code executed to be inside a {...} group. Finally, I have no idea what you were trying to do with \pgfmathsetseed.

\documentclass[]{article}
\usepackage{tikz}
\begin{document}

\begin{tikzpicture}
 % size of circle
 \def \radius {2cm}
 \def \margin {8}
 % number of vertices
 \def \n {5}
 % Probability for an edge to show up between vertices
 \def \p {0.5}

 % Drawing the vertices/nodes
 \foreach \s in {1,...,\n}
  \node[draw, circle] (\s) at ({360/\n * (\s - 1)}:\radius) {};

 % Drawing the edges
 \foreach \s in {1,...,\n}{
  \foreach \t in {\s,...,\n} {
    % Generate and store a random number to the variable \dummynum
    \pgfmathparse{rnd}
    %\let\dummynum=\pgfmathresult
    % If dummynum is less than p, edge is drawn; otherwise nothing happens
    \ifdim\pgfmathresult pt < \p pt\relax \draw (\t) -- (\s);\fi
  }}
\end{tikzpicture}

\end{document}