Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Write a function that generates one of 3 numbers according to given probabilities

# Write a function that generates one of 3 numbers according to given probabilities
# https://www.geeksforgeeks.org/write-a-function-to-generate-3-numbers-according-to-given-probabilities/
# Given a function rand(a, b) which generate equiprobable random numbers between [a, b] inclusive. Generate 3 numbers x, y, z with probability P(x), P(y), P(z) such that P(x) + P(y) + P(z) = 1 using the given rand(a, b) function 
# Let the given probabilities be in percentage form, like P(x) = 40%, P(y) = 25%, P(z) = 35%.

# Following steps:
# 1. Generate a random number between 1 to 100. Since they are equiprobable, the probability of each number is 1/100
# 2. Following are some important points to note about generated random number 'r'
    # a. 'r' is smaller than or equal to P(x) with probability P(x) / 100
    # b. 'r' is greater than P(x) and smaller than or equal P(x) + P(y) with P(y) / 100
    # c. 'r' is greater than P(x) + P(y) and smaller than or equal 100 (or P(x) + P(y) + P(z)) with probability P(z) / 100
    
# This function generates 'x' with probability px/100, 'y' with probability py/100, and 'z' with probability pz/100; Assumption: px + py + pz = 100 where px, py and pz lie between 0 to 100
def random(x, y, z, px, py, pz):
    # Generate a number from 1 to 100
    import random 
    r = random.randint(1, 100)
    
    # r is smaller than px with probability px/100
    if r <= px:
        return x
    # r is greater than px and smaller than or equal to px+py with probability py/100
    elif r <= px + py:
        return y
    # r is greater than px+py and smaller than or equal to 100 with probability pz/100
    else:
        return z
    

Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.