Search code examples
pythonalgorithmrandomprobability

Algorithm to execute a function only 12% of all cases


I have a function and I want to let it do things only in 12% of the cases I call it.

I already wrote a function that works, but it's not accurate enough.

Example in Python:

# probability to execute the function is 50%
percent_probability = 50

frequency = 100 / percent_probability

r = random.randint(1, frequency)

if r == 1:
   my_function()

This works for percentages like 10%, 20%, etc. but not for 33% because it gets rounded.

How can I do this properly?


Solution

  • I would use random.random() for this, like so:

    if random.random() < anz_prozent_wahrscheinlichkeit / 100.:
       execute my function()
    

    This uses floating-point maths and is therefore not restricted to integer percentages (for example, anz_prozent_wahrscheinlichkeit = 0.1 would work correctly).