1

I have a variable, x, and I want to set it to the values either 1 or 2, with a 60% probability x=1 and a 40% x=2.

I'm doing this in a class, so x should regenerate each time a button is clicked and I'll then plot it, but I'm not sure how to set it using specific probabilities. I know I could do it randomly but that's not quite what I want.

Does anyone know how to do this?

confusedcoder
  • 21
  • 1
  • 5
  • Possible duplicate of [A weighted version of random.choice](http://stackoverflow.com/questions/3679694/a-weighted-version-of-random-choice) – sobolevn Dec 03 '15 at 15:29
  • also http://stackoverflow.com/questions/4265988/generate-random-numbers-with-a-given-numerical-distribution – sobolevn Dec 03 '15 at 15:29

3 Answers3

2

Random uses a uniform distribution, so you can use it like this :

x = 1 if random.random() < 0.6 else 2
ploutch
  • 1,204
  • 10
  • 12
1

You just take a random value, check if it is less than desired probablility, and return the first or the second option:

def random_choice(val1, val2, probability_of_val1):
    return val1 if random.random() < probability_of_val1 else val2
Ihor Pomaranskyy
  • 5,437
  • 34
  • 37
0

A simple strategy could be the following:

  1. generate a random number between 0-1
  2. if random number is greater than 0.6 assign value 2
  3. else assign value 1

Python code to do this:

import random
if random.random() > 0.6:
  x = 2
else:
  x = 1
sanchitarora
  • 882
  • 9
  • 18