Jump to content

[SOLVED] Why's "math.random() > 0.01" not working?


Recommended Posts

Hello, I need help :).

So, this's the code I need help with.

elseif food and food.components.edible and food.components.edible.foodtype == "MEAT" and not inst.components.sanity:IsSane() and math.random() > 0.99 then
inst.components.hunger:DoDelta(2)
inst.components.health:DoDelta(2)
inst.components.sanity:DoDelta(2)
elseif food and food.components.edible and food.components.edible.foodtype == "MEAT" and not inst.components.sanity:IsSane() and math.random() > 0.01 then
inst.sg:GoToState("hit")
inst.components.hunger:DoDelta(2)
inst.components.health:DoDelta(-8)
inst.components.sanity:DoDelta(-2)
inst.components.talker:Say("GrYyAh, OuR tOnGuE gOt HuRtEd!!!")

So, the code on top's supposed to have a 99% chance of happening while the one on the bottom's supposed to have a 1% chance of happening, but when I go in the game it's almost like the code on the bottom's the one with 99% chance of happening?!

Can someone please explain to me how "math.random() > 0.00" works?

Edited by SuperDavid
Link to comment
Share on other sites

Currently your first if has a 0.01 chance of happening.

And if it doesn't happen, then you have a 0.99 chance of the second if happening.

So you end up having a 0.99 * 0.01 = 0.0099 chance of nothing happening (entering no if).

So two things here.

First thing:

math.random() returns a number between 0 and 1.

If you call math.random() multiple times, you are going to obtain different numbers every time.

It's like having 0.5 > 0.99 on the first if, and 0.2 > 0.01 in the second if.

You want to roll a die once, then act upon that result.

local chance = math.random()

if chance < 0.25 then
	-- Do this
	-- chance is 25%
else
	-- Do that
	-- chance is 75%
end

if chance < 0.25 then
	-- Do this
	-- chance is 25%
elseif chance >= 0.25 and chance < 0.50 then
	-- Do that
	-- chance is 25%
else
	-- Do whatever
	-- chance is 50%
end

Second thing:

The function returns a number between 0 and 1.

The function has a uniform distribution (this means the probability to get any of the numbers is the same).

math.random() > 0.99 has a 0.01 chance, of happening. Since you can get 0, 0.1, 0.2, 0.314, 0.56789, and all of those are lower than 0.99.

math.random() > 0.01 is highly likely, since you need a 0 or a number very close to 0, and 0.1, 0.2, 0.314, 0.56789 are all higher than 0.01.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
  • Create New...