# TikZ random messes with coordinates

I'm trying to draw random points in a polar coordinate system with lines leading down to a circle. This is absolutely straightforward, but the result is not as expected. There seems to be an interference between the random functions provided by TikZ and the polar system.

Under XeLaTeX, the following MWE:

\documentclass{standalone}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
\draw (0,0) circle (1);
\foreach \myangle in {0, 20, ..., 340} {
\draw (\myangle:{random(0.5, 2)}) -- (\myangle:1);
};
\end{tikzpicture}
\begin{tikzpicture}
\draw (0,0) circle (1);
\foreach \myangle in {0, 20, ..., 340} {
\draw (\myangle:{2*rnd + 0.5}) -- (\myangle:1);
};
\end{tikzpicture}
\end{document}


produces:

• Because I use XeLaTeX for the remainder of the text. In past problems, I found that XeLaTeX does not have smooth support for tikz, hence the additional information. – Huang_d Apr 21 '19 at 14:11
• random(x ,y ) generates a random integer, see p. 1009 of the pgfmanual. You cannot use a noninteger for x if you use more than one variable. – user121799 Apr 21 '19 at 14:37
• @marmot good observation, but that doesn't explain the behaviour that the lines do not radiate outwards as expected from polar coordinates – Huang_d Apr 21 '19 at 14:43
• Yes, because there is an additional expansion issue. – user121799 Apr 21 '19 at 14:50

I admit that this is somewhat confusing. There are two issues here:

• integer vs. noninteger;
• expansion.

As for the first issue, random, when used with two arguments, expects these arguments to be integers. It then returns an integer. If you do not use arguments, it returns a real number between 0 and 1. This is described in detail on pages 1008-1009 of the pgfmanual. Once you feed it with a noninteger it doesn't know what to do and just returns the noninteger, i.e. 0.5 in this case. This issue is not related to xelatex, but pdflatex yields the same output. I believe you are looking for {1.5*random() + 0.5} (or {1.5*rnd + 0.5}).

And then there are expansion issue. I believe I had an answer on this one somewhere, but do not remember where. Basically, you have to force TikZ to pin down the random number rather than leaving it random.

The following code resolves these issues.

\documentclass{standalone}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
\draw (0,0) circle (1);
\foreach \myangle in {0, 20, ..., 340} {
\pgfmathsetmacro{\myrnd}{1.5*random() + 0.5}
\edef\temp{\noexpand\draw (\myangle:\myrnd) -- (\myangle:1);}
\temp
};
\end{tikzpicture}
\end{document}


• Oh wonderful, that resolves it. – Huang_d Apr 21 '19 at 14:54