Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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?

share|improve this question
    
Have you tried specifying the seed: \pgfmathsetseed{} –  Peter Grill Jan 23 '12 at 21:36
    
I did, it doesn't help. I guess every time I call "myrandomnumber", it is replaced with "rnd" and generates a different random number. –  Freddy Jan 23 '12 at 21:39
    
If you want to use the same random multiple times in the same run, the @Jake's solution should work. If you want to obtain the same "random" results each time you run then you should use \pgfmathsetseed{}. –  Peter Grill Jan 23 '12 at 22:03
add comment

2 Answers 2

You should save the result of the rnd operator to a macro. The easiest way to do that is to say \pgfmathsetmacro<\macroname>{rnd}. Then you can use the random number where you need it (like \draw (0,0) -- (<\macroname>,<\macroname>);), and draw a new one by repeating the \pgfmathsetmacro... command.

share|improve this answer
add comment

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}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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