# Storing the result of a random number in tikzpicture

I am drawing a surface composed of rigid "molecules" composed of three spheres each. I want to add some randomness to the surface. I have created this code:

\begin{tikzpicture}
\def\nuPi{3.1459265}
\foreach \i in {11,10,...,0}{
\foreach \j in {5,4,...,0}{
\def\dx{rand*0.1}
\def\dy{rand*0.1}
}
}

\end{tikzpicture}


judging by the resulting surface, the \dx and \dy are generated each time they are accessed and not once in each loop. Is there a way to store them?

-

You can store the results using \pgfmathsetmacro{<macro>}{<expression>}. Note that the the argument to functions like sin(<arg>) should be given in degrees by default. If not, you should use the "r operator". For more on parsing mathematical expressions, read section 63 Syntax for mathematical expressions (p 527 onward) in the tikz/pgf documentation.

I've modified you code snippet into an MWE and used (\xcoor,\ycoor) to represent the coordinate pair, since they were basically the same for the three shaded balls.

\documentclass{article}
\usepackage{tikz}% http://ctan.org/pkg/pgf
\begin{document}
\begin{tikzpicture}
\foreach \i in {0,1,...,11}{
\foreach \j in {5,4,...,0}{
\pgfmathsetmacro{\xcoor}{\i+rand*0.1}% x-coordinate
\pgfmathsetmacro{\ycoor}{0.5*\j+rand*0.1+.4*sin(\i*360/12)}% y-coordinate

@Yotam: I've updated my answer. The argument of sin has to be an angle in degrees. If you want to specify it in radians, you need to use the r operator. –  Werner Jan 9 '12 at 21:30