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$
1
  • $\begingroup$ Show@Table[ With[{c = RandomReal[{1, 2}]}, Plot[Sin[c \[Pi] x], {x, 0, 1}]], 10] ? $\endgroup$ Apr 13, 2018 at 16:22

1 Answer 1

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$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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