How to Calculate Probability With Percentage?

Hi, dear all…

sorry for my english,

i have little question,
if i have a setting of chance using percentage number

i wanna the hit chance meet the setting,
here is my code, but it’s not meet request.

percentage = 80 #it's mean 80%

hitcount = 0
for n <- 0..100 do
    needAppear = :rand.uniform( 100 )
    if needAppear >= percentage, do: hitcount = hitcount + 1

# i wanna the 100 times hit 80 times
assert hitcount == 80

how do i fix it?

thanks for help :smiley:

This is backwards :slight_smile: You want:

needAppear <= percentage

In your version, it will succeed ~1/5th of the time (20 numbers greater than 80, less than 101). So reverse them…

Beyond that … the for loop creates a list of results. You probably don’t really want that here (even if this is just test / play code) … try something like:

Enum.reduce(0..100, 0,
 fn _, acc ->
   if :rand.uniform(100) < 80 do
     acc + 1

What is the case? Why did you use :rand.uniform(100) when you want a specific count? Random number mean it can’t be determined, thus making it less likely to hit your expectation.

1 Like

Yeah this test case doesn’t make a lot of sense. Just that something has an 80% chance doesn’t mean that it will hit 80 out of 100 times EXACTLY if you are actually using random numbers.

1 Like

Sorry, let me describe more clearly,
i need to control the probability of a event need happen or not

I did not think it was very thoughtful,
just very simple to think that I can use this way to calculate the results

if random number is greater than percentage, it should happen

maybe i need change code like this way?

percentage = 80
isNeedHappen = false

chance = :rand.unifrom( 100 )

if chance <= percentage, do: isNeedHappen = true

Its still not clear how often that even shall occur.

Once you tell it should happen if random number is bigger than 80, the other time you say it hass a chance of 80%. Thats not the sam! The first variant will mean a chance of 20%.

But in general its roughly like this:

def random_with_chance(chance), do: :rand.undiform(100) <= chance

This will return true with a chance of chance in 100.

Be aware that you will not have exactly 80 true after calling it a hundred times, because of the nature of randomness.

1 Like

almost close to 80 is meet my request
that’s exactly what I want :smile:

thanks for help :smiley: