Skip to content Skip to sidebar Skip to footer

Returning A Value At Random Based On A Probability Weights

Possible Duplicate: A weighted version of random.choice Let's say for simplicity a function takes in 4 inputs: 2 names and their respective 'bias/weights', how can I write a fun

Solution 1:

I've modified the function to accept an arbitrary number of inputs and weighted probabilities so if later on you decide you want to use more than two inputs, you can.

import random

defmyRand(i, w):
    r = random.uniform(0, sum(w))

    # loop through a list of inputs and max cutoff values, returning# the first value for which the random num r is less than the cutoff valuefor n,v inmap(None, i,[sum(w[:x+1]) for x inrange(len(w))]):
        if r < v:
            return n

Example usage:

inputs = ['e', 'f', 'g', 'h']
weights = [10, 30, 50, 10]

print myRand(inputs, weights)

Solution 2:

This would accomplish what you're trying to do:

#assumes p_a and p_b are both positive numbers that sum to 100defmyRand(a, p_a, b, p_b):
   return a if random.uniform(0,100) < p_a else b 

Note that p_b becomes unnecessary in your special case of having only 2 weights, since p_b == 100-p_a.

Solution 3:

a = 'x';b = 'y';p_a = 10;p_b = 90

ratio = p_a+pb = 100

generate a random number between 0 and 100 and if the number is less than 10 use a=>x else use b=>y

Post a Comment for "Returning A Value At Random Based On A Probability Weights"