0
$\begingroup$

I want to generate (and eventually sample) a sine wave with a random frequency in the range [½, 1] (i.e. capture somewhere between half and one period of the waveform over the domain [0,1]).

The two extremes for this are

Plot[Sin[ \[Pi] x], {x, 0, 1}]

and

Plot[Sin[2 \[Pi] x], {x, 0, 1}]

My initial effort for this was to replace the 2 with a call to RandomReal[{1, 2}], but this results in a different random value being used for every x.

Putting the call to RandomReal in a block has the same behavior:

Plot[Block[{m = RandomReal[{1, 2}]}, Sin[m \[Pi] x]], {x, 0, 1}]

Plot with RandomReal

How can I force Mathematica to only evaluate RandomReal once so I get a single clean sine wave out?

$\endgroup$
  • $\begingroup$ Show@Table[ With[{c = RandomReal[{1, 2}]}, Plot[Sin[c \[Pi] x], {x, 0, 1}]], 10] ? $\endgroup$ – Okkes Dulgerci Apr 13 '18 at 16:22
4
$\begingroup$

This will give what I think you expect, it uses a different value for every evaluation:

With[{c = RandomReal[{1, 2}]},
  Plot[Sin[c \[Pi] x], {x, 0, 1}]
]

you could just as well use Block or Module for this case, but With is probably a bit clearer...

$\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.