How to get a single evaluation of RandomReal in a Block

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}]


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

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

1 Answer

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