[Tex/LaTex] Defining variables in TikZ

random numberstikz-pgf

I'm trying to define random variables – for example to draw some random points of the form (r,r) when r is a random number. I tried \def\myrandomnumber{rnd}, but that seems to give me a new random number every time. What's to be done?

Best Answer

Here is an example of using \pgfmathsetseed{} to ensure that subsequent runs yield identical results with a random number. I also make use of Jake's solution using \pgfmathsetmacro to store the result so that it can be used more than once.

Depending on when you run this, the blue pictures will vary (since \pgfmathsetseed{} was not used), but the red ones should not change. Since each of the red images are identical it is obvious that the random numbers did not change between runs, but note that each of the three blue pictures are different.

enter image description here

\documentclass{article}
\usepackage{tikz}

\newcommand*{\RandomLine}[1][red]{
\begin{tikzpicture}
    \pgfmathsetmacro{\Xa}{random(7)}
    \pgfmathsetmacro{\Ya}{random(7)}
    \pgfmathsetmacro{\Xb}{random(7)}
    \pgfmathsetmacro{\Yb}{random(7)}

    \draw [ultra thick, out=120, in=60,#1] (\Xa,\Ya) to (\Xb,\Yb);
    \draw [ultra thick, out=230, in=19,#1] (\Xa,\Ya) to (\Xb,\Yb);
    \end{tikzpicture}
}

\begin{document}
\RandomLine[blue]
\RandomLine[blue]
\RandomLine[blue]

\pgfmathsetseed{1138}\RandomLine[red]
\pgfmathsetseed{1138}\RandomLine[red]
\pgfmathsetseed{1138}\RandomLine[red]
\end{document}