I am looking for a way of generating booleans rapidly. For booleans, one usually uses random(0,2);
but in my case I need about 250 booleans and calling random every time is slow.
So I thought about using all bits of a random number on the whole range as such:
randomSeed(100); // A seed to always keep the same sequence
long rdm = random(MIN,MAX); // Generate a number in range MIN,MAX of type long
long mask = 1;
for(int i=0; i<32; i++){
if((rdm>>i)&mask){
//do something
} else {
//do something else
}
}
But with this I have three questions:
- What are MIN and MAX so that the LONG random uses all bits, with value ranging from -2,147,483,648 to 2,147,483,647 (arduino long type). I tried several MIN and MAX, also simply
random();
but without success. - Is it a valid approach? Do I expect each bit to be uniformly distributed? Should I use fewer bits, e.g.
random(0, 2^16);
for a "better" distribution? - Is there some seed known to be good or bad at this?
My project
I am working on a device made of Neopixel LED strips. It is for a visual neuroscience experiment where each "pixel" is either ON or OFF. I need the speed to be able to reach high refresh rate (60-100Hz), with normal statistical distribution to avoid bias in neuron response analysis. With this approach, I can reach the desired speed but I'm concerned about the statistics. So I need a better understanding of random()
's behaviour to do it right!
random()
, which has 31 usable bits, over the one from the Arduino core, which only adds bugs. And I strongly recommend you test for the statistical properties you care about before committing to any PRNG.random()
then to have the 31 bits. I'm using fixed seeds so I'm also checking how they distribute.