I Made a lot of scripts using math.random() and most times it will only do one thing and not the other thing
Is there something else which will do a 50/50 chance and will be fair with both values?
Random
is a feature that is different from math.random()
, perhaps you could use it? It was introduced 3 years ago:
The other thing you need to think about is the count of outcomes. Thus you need to check for the condition of the output to choose A/B. Oh, and if the random is not truly random, set the math.randomseed(seed)
to something, such as os.clock()
.
I thought they changed math.random()
's algorithm to the same one that Random
uses years ago.
It is now. They are exactly the same algorithm. There was a post which explained its differences well:
No, that’s just the way it is. There’s a 1 in 2 chance of retrieving one thing rather than another, this is susceptible of continuously picking the same result. For example, if you asked 10 people to pick between 1 and 2 there is a chance all will be 2.
However, you could potentially force it to choose the 2nd option if the 1st is chosen more than 3 times.
ie.
local last_picked = {};
local function last_three_equal(n)
local total_picked = #last_picked;
for i = total_picked, total_picked - 3, -1 do
if (last_picked[i] ~= n) then
return false;
end
end
return true;
end
local function pick_option()
local picked = math.random(2); --// Picks between [1, n]
if (last_three_equal(picked)) then
return picked == 2 and 1 or 2;
end
return picked;
end