How would I make something have a 5% chance of happening with math.random()?

I’m currently working on making a generator have a 5% chance to break every 30 minutes. Unfortunately, I’m not quite sure how I would make that happen. I’ve tried making a table of numbers and using an if statement but those didn’t work. I’ve put where the problem is down below. When the script does actually pick 1,2,3,4, or 5, the next part doesn’t run and there are no errors in the output. What should I change?

local Break = {1,2,3,4,5}

while true do
	wait(2) -- 2 seconds for the time being so I don't have to wait 30 minutes
	local Chance = math.random(1, 100)
	print(Chance)
	if Chance == Break and broken.Value == false then
6 Likes

% is 100. So, 5 % = 5 / 100 chance = 1/20. You initiate math.random(1,20) and you get 1 of 20 = 5 of 100 that event would happen. Your current chance is incorrect.

while true do
	wait(2) -- 2 seconds for the time being so I don't have to wait 30 minutes
	local Chance = math.random(1, 20)
	if Chance == 1 and broken.Value == false then
                    .....
6 Likes

Something you could do is like the following:

local MINUTES = 30 --(Or in your case some smaller number)
while wait(60 * MINUTES)
     local probability = math.random(1, 100)
     if (probability >= 1 and probability <= 5) then
          broken.Value = true -- No need to test the Value as if it is already true it'll just be set true a second time
     end
end
2 Likes

The reason this isn’t working is because you’re comparing a Table to a Number, these are never equivalent. {1, 2, 3, 4, 5} ~= 1

% is 100. So, 5 % = 5 / 100 chance = 1/20. You initiate math.random(1,20) and you get 1 of 20 = 5 of 100 that event would happen. Your current chance is incorrect.

@Nikita39Gamer His chance is completely correct, 5/100 == 5%, as does 1/20 == 5%, either way is completely fine.

2 Likes

Thanks! I’m trying it now (extra words so i can actually comment)

1 Like

This is also very helpful. Thanks a lot

1 Like

Well, i meant his chance checking is incorrect. Like as you said he tried to compare integer with table and never successed

1 Like

Yeah I see my mistake now. My bad

Also yes this did work. Thanks for the help (you too M9_Sigma)