# Random number generator



## kotori (Jun 5, 2007)

Because of this post on the NI Forum I thought I'd post some simple random number generator code. While the builtin random function works well there is no way to specify a seed. By being able to specify a seed one can make sure that a script behaves the same each time a song is played or make it possible for two identical scripts which run in parallel is fed the same MIDI data to see the same random sequence.

Here's a very simple linear congruential generator. I fetched the constants from some other web page so I haven't myself verified that they generate a full cycle. I'm sure there's room for improvement but it might be enough in simple cases. The code is to be compiled using my script editor:

_{ ------ random functions ------- }_
*function* seed(s)
``rand_a := s
*end function*

*function* *rand(*min, max, result)``
``*declare* global rand_a
``rand_a := (rand_a * 125) mod 2796203
``result := rand_a mod (max - min + 1) + min
*end function*

_{ ------- usage example -------- }_
*on init*
``*declare* x
``_{ The value is used to initialize the random number generator. 
If it is a constant value one will get the same random sequence each time.
If this is not desireable one can pass for example $ENGINE_UPTIME as parameter. }_
``seed(10)````````
*end on*

*on note*
``*rand(*1, 100, x) _{ generate a random number between 1 and 100 and store it in x }_
``message(x)
*end on*


----------



## Thonex (Jun 6, 2007)

Very cool Nils!!

The idea of having a random values assigned to filter cutoff and resonance across multiple patches while staying "in sync" is very appealing.

Thanks for sharing this.

Cheers.

T


----------

