How to produce a real random value between two prescribed values ?
kevinspace
Posts: 56
Hello everyone~
Are there anyone know that how to produce a real random value between two prescribed values ?
Just like it :
a := random ( Minimum, Maximum )
Are there any example or any suggestion?
Thanks a lot.
Are there anyone know that how to produce a real random value between two prescribed values ?
Just like it :
a := random ( Minimum, Maximum )
Are there any example or any suggestion?
Thanks a lot.
Comments
I think the question is a bit to simple to give a good answer!
1. Can you live with restrictions in which values you can pass as Minimum and Maximum? For example if you can live with the fact that (Maximum - Minimum) has to be a "2 to the power of x"- value ( for example 2,4,8,16,32 ...) then it is easy.
2. If not, can you live with restrictions in "real randomness"? The problem is that in case you map a 32bit real random number as generated with Chips RealRandom object, which has a equal probability for each number in the 32 bit-range, to a range that does not have 2 to the power of x elements, you loose "equal probability" due to rounding and some values have a slightly bigger probability than others.
So, if you can live with 1. you simply do:
(realRandomValue & (Maximum-Minimum-1)) + Minimum
again .. the allowed values for Maximum is limited to (Minimum + 2^x)
If you can live with 2. new questions have to be asked:
What is the max. range? In general it is easy: (realRandomValue / maxRandomValue) * (Maximum - Minimum) + Minimum
If you really want real random numbers and with any range it's getting complex!
This uses the Propeller's pseudo-random number generator with the global long variable seed. If you need "true" random numbers, you can also use the RealRandom object from the OBEX instead. Although the modulus operator (//) introduces a tiny bit of bias into the results, the effect will be minimal for small values of max_val - min_val.
-Phil
(and then using Phil's code above to put it in the desired range).
It's sort of like the observer-influence in quantum randomness. Good for "fair" games of chance, if you were making slots or roulette for example.
http://forums.parallax.com/showthread.php?136727-Random-Number-between-1-100