Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random choice with negative weights [closed]

Tags:

python

random

In my python program, I have three variables a, b and c. They are all floats, and may be positive or negative with no upper and lower bounds.

How would I go about devising a function that takes these variables as weights and randomly chooses a corresponding action (A, B & C)?

Example:

a = 10
b = -2
c = 7

The function should perform A most of the time, C some times, and B the least often.

The 'weighted random functions' I found on this site do not deal with negative weights.

like image 1000
medakk Avatar asked May 02 '26 17:05

medakk


2 Answers

weights = [10, -2, 7]
offset = min(weights)
positiveweights = [z - offset + 1 for z in weights]

Now you can use any weighted random function that requires positive weights.

like image 138
nekomatic Avatar answered May 05 '26 07:05

nekomatic


Well, an easy way is to assume that the values of your variables come from a normal distribution with the mean equal to largest value(*) and an arbitrary standard deviation (e.g. sd=1).

Then, what you need to do is simply to find the probability of seeing a specific value such as -2 which can be solved by probability distribution function (pdf). Then you can use the probabilities as weights.

The good thing about this method is that you can have also negative values.

Solution:

import scipy.stats
variables = [10, -2, 7]
maximum = max(variables)
probabilities = scipy.stats.norm(maximum, 1).pdf([variables])

Result: array([[ 3.98942280e-01, 2.14638374e-32, 4.43184841e-03]])

The rest, you can figure out yourself.

(*) The reason for setting the meanto the largest value is to get the largest probability (weight) for it.

like image 30
Dataman Avatar answered May 05 '26 07:05

Dataman