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
end
# i wanna the 100 times hit 80 times
assert hitcount == 80
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
else
acc
end
end
)
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.
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.
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%.