Checking a chance

Let’s say I had a percentage chance, for example 25%, how could I make a function to return true 25% of the time and false 75% of the time?
I am currently using this:

if math.random(1, 100) <= chance then
    return true
else
    return false
end

This works fine, but it won’t work with percentages lower than 1, eg. 0.97%. Thanks for any help!

1 Like

If you’re using multiple percentages, I would recommend scripting a weighted table, however, if you’re just checking one percentage, use this:

if Random.new():NextNumber(0, 100) <= 0.97 then
	return true
else
	return false
end

A more concise way to write it is to do this:

return Random.new():NextNumber(0, 100) <= 0.97
1 Like

but then wouldn’t there be 101 integers between 0 and 1? wouldn’t this make it uneven? like a 50% chance would have a 50/101 to return false and a 51/101 to return true?

1 Like

uh, what is the 101st one??

limit

1 Like

If you want to randomly return true 25% of the time you can do this:

if math.random(1, 4) == 1 then
    return true
else
    return false
end

If you wanted to things like .97%, you could use this

if math.random(1, 1000) <= 97 then
    return true
else
    return false
end

So for your code, let’s say chance is 0.973 for instance. this would work:

local chance =  0.973 -- 100 = 100%

if math.random(1, 100000) <= chance * 1000 then
    return true
else
    return false
end
1 Like

0-100 is 101 combinations right?

how could I turn this into a function that works with any amount of decimals in the percentage?

1 Like

This function takes in a number between 0 and 100 (it also accepts above 100 but that will always return true), and returns either true or false.

function randomPercentage(chance)
	local decimalPlaces = 6 -- every zero is another decimal place supported
	return math.random(1, 100 * 10 ^ decimalPlaces) <= chance * 10 ^ decimalPlaces
end

The function supports up to 6 decimal places e.g. 0.123456. any decimals after that are just ignored. If you need more than 6 decimal places, change the value of decimalPlaces.

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.