jeudi 29 juillet 2021

Lua PRNG results repeating numbers in succession

I'm attempting to pick a number, either 1 or 2.

1 = bob wins, 2 = alice wins.

When iterating over 10000~ attempts, there appears to be a high 'streak' of repeating numbers, for example 1 being repeated 15-20 times in a row.. This doesn't seem right, is this too high?

Example code:

local bobWins = 0
local aliceWins = 0

local bobWinStreak = 0
local aliceWinStreak = 0

local bobHighestStreak = 0
local aliceHighestStreak = 0

local lastWinner = ""

for i=1,10000 do
  local num = math.random(1,2)

  if num == 1 then winner = "bob" else winner = "alice" end

  if winner == "bob" then
    bobWins = bobWins + 1
    if lastWinner == "bob" then
        bobWinStreak = bobWinStreak + 1
        aliceWinStreak = 0

        if bobWinStreak > bobHighestStreak then
          bobHighestStreak = bobWinStreak
        end
    end
  else
    aliceWins = aliceWins + 1

    if lastWinner == "alice" then
        aliceWinStreak = aliceWinStreak + 1
        bobWinStreak = 0

        if aliceWinStreak > aliceHighestStreak then
          aliceHighestStreak = aliceWinStreak
        end
    end
  end

  lastWinner = winner
end
print("BOB WINS: " .. bobWins,"BOB HIGHEST STREAK: " .. bobHighestStreak)
print("ALICE WINS: " .. aliceWins, "ALICE HIGHEST STREAK: ".. aliceHighestStreak)

Example output:

BOB WINS: 5036  BOB HIGHEST STREAK: 25
ALICE WINS: 4964    ALICE HIGHEST STREAK: 19

Is this normal to expect, 15-20 (25 in the given example) bob wins in succession and vice versa for alice? How can I achieve a more fair 50/50 result? The spread/distribution between the two are OK (5036:4964 is tolerable and pretty 50:50 I would say) but I personally wouldn't have expected more than say 5/6 in a row..

Furthermore, increasing the iterations does change the streak numbers (albeit slightly), but not by a huge amount.. 10,000,000 iterations returns a streak of 30-35 on average...




Aucun commentaire:

Enregistrer un commentaire