2
$\begingroup$

This is probably really a simple question.

I would like to plot a sum of cosines with increased argument and for each cosine in sum I would like to add random value:

Plot[Sum[Cos[n*x + RandomReal[{0, 2 Pi}]], {n, 100}], {x, -10, 10}]

However it seems to me that the program, while making a plot, generates a new random number for each x-point plotted. Therefore, even for single cosine (Plot[Cos[x + RandomReal[{0, 2*Pi}]], {x, -10, 10}] ) I get a completely noisy graph of random cosine values.

I would be very grateful if somebody can tell me what to do to prevent the program from generating new random numbers at each x-point.

$\endgroup$
  • 3
    $\begingroup$ Just compute the random offset once: With[{r = RandomReal[{0, 2 Pi}]}, Plot[Cos[x + r], {x, -10, 10}]] $\endgroup$ – J. M. is away Mar 29 '17 at 10:55
  • $\begingroup$ Thank you for answer. I tried it before, but then the problem is that i have the same random number for each cosine in my sum. And i would like to generate a new one for each (but not for each x when plotting). $\endgroup$ – Maciek Kowalczyk Mar 29 '17 at 11:08
  • 3
    $\begingroup$ Generate as many as you need: With[{r = RandomReal[{0, 2 Pi}, 10]}, Plot[Total[Cos[Range[10] x + r]] // Evaluate, {x, -10, 10}]] $\endgroup$ – J. M. is away Mar 29 '17 at 11:14
2
$\begingroup$

J.M. has answered the question in the comments. This is to get that answer (slightly edited) on record in a more visible form. For 10 terms, we get

SeedRandom[42];
  With[{n = 10},
    With[{r = RandomReal[{0, 2 Pi}, n]}, 
      Plot[Total[Cos[Range[n] x + r]], {x, -10, 10}]]]

plot1

For a 100 terms, which is what the OP asked for, the plot must be stretched out to see the details better.

SeedRandom[42];
  With[{n = 100},
    With[{r = RandomReal[{0, 2 Pi}, n]}, 
      Plot[Total[Cos[Range[n] x + r]], {x, -10, 10},
        AspectRatio -> 1/5,
        ImageSize -> Full]]]

plot2

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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