B4J Question Random bit

ElliotHC

Active Member
Licensed User
Hi,

I need to generate a random bit, or number essentially 0 or 1 but I need to do it every 1ms. Is this too fast for B4J? I am concerned that the random generator isn't actually random. Does anyone know how it's generated?

Thanks
 
Last edited:

William Lancee

Well-Known Member
Licensed User
Longtime User
B4X:
    markTime = DateTime.Now
    Dim ntrue, nfalse As Int
    Dim rbit As Boolean
    For i = 1 To 1000000
        rbit = Rnd(0, 2) = 1
        If rbit = True Then ntrue = ntrue  + 1 Else nfalse = nfalse + 1
    Next
    Log(ntrue & TAB & nfalse & TAB & (DateTime.Now - markTime))  'a million bits in about 30 milliseconds - fast enough?
 
Upvote 0

William Lancee

Well-Known Member
Licensed User
Longtime User
I know how pseudo random numbers are generated. It starts with a long integer. When the program starts this 'seed' depends on the system clock,.
This seed can be specified by you for if you want the same random sequence (for debugging purposes or other reasons).
RndSeed(number as long) called at the start of a sequence will always result in the same random sequence.

At each call the seed is multiplied by a large number and the upper overflow bits are thrown away. The number is converted to the requested range before being returned.
The seed is updated by this process to be ready for the next call. I presume that Rnd(min, max+1) uses this method. If an outsider doesn't know the seed, the randomness is unpredictable (but not random since each result is part of a fixed number sequence). That is why secure random number generators make this predicting task much harder.

In my academic career, I have rarely needed an NON-pseudo random number generator. But such situations exist. In those cases, you have to use something that is truly random. I once used the time between key presses as a seed before making each Rnd() call. [Although, technically, if one were to know the neural/muscular processes leading to time between keypresses, the sequence would still be called pseudo-random]
 
Upvote 0
Top