Randomizing the random seed with computer clock/timer?

Hello,
In other programming languages there is a way to randomize the random seed using computer clock/timer, such as (in Visual Basic) we can use: randomize timer.

Is there anyway in Sonic Pi we can do this with “with_random_seed” where the seed is taken from computer clock/timer? At least the random sequence won’t be as predictable as the pseudorandom in Sonic Pi.

Thanks

Hi there,

I use the following to randomise my random seeds between runs. It uses UTC:

use_random_seed Time.new.to_i

You can easily adapt this for use with with_random_seed within runs.

I hope this helps!

Oh you can? I couldn’t find “time” in the documentation. Did I miss this one again? Anyway, thanks, it helps.

Strictly speaking, Time is not part of the Sonic Pi language per se.
Sonic Pi is built on top of Ruby, so some things from plain Ruby may still be available, but there are no guarantees that they will work, or if they do, whether they will continue to do so down the track. ‘Let the buyer beware’ :slightly_smiling_face:

1 Like

Oh. So there is no guarantee that such Ruby instructions/commands could continue to be supported in the future. Noted. Thanks.

I’v used this snippet a lot inside live_loops to ensure that things are random:

live_loop :some_loop do 
  SecureRandom.random_number(1000).times { rand }
  # Do something else
end

This is just randomly consuming some random numbers. Not sure why, but I’v noticed that if you use only that “use_random_seed = Time.now.to_i” things are still not always random at least if you are using multiple threads.

Test this. It’s still pseudo random. If you repeat the random a few times, you’ll notice the pattern. Using Time.now.to_i is better, never repeat the same sequence twice.

SecureRandom.random_number(1000).times
loop do
  print rand_i(100)
  sleep 1
end

when I run this, my computer always gives: 75, 73, 46, 24, etc.

You are missing the { rand } from the end, which consumes the random numbers. If you try:

loop do
  print SecureRandom.random_number(1000)
end

You can see that it produces random numbers. To consume random numbers use it with rand:

SecureRandom.random_number(1000).times { rand }

This calls rand 0-1000 times, and thus consumes some random numbers and in a way generated new subset of random numbers from certain seed. You can also use it as:

use_random_seed SecureRandom.random_number(100)

If you want seed between 0-100.

You could make that slightly more efficient by doing:

live_loop :some_loop do 
  rand_skip SecureRandom.random_number(1000)
  # Do something else
end
1 Like

Thanks! Good idea. Was not aware of such method. Should really go trough that lang list again :slight_smile:

OK, test this, it did produce random number and not the same sequence everytime I ran it. Thanks.

I’ve also tested this and it did produce random number and not the same sequence everytime I ran it. Thanks.