Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generating random numbers in python with percentage function on what selected value in python

Tags:

python

random

Lets say I wanted to generate a random number in python using something like random.randint(1,100) but how would I go about making Python want to tend toward selecting higher random numbers? So like if i wanted 80% of numbers above 50 to be chosen with 20% of numbers below 50 to be chosen. like a casino slot machine probability. (we all know there not truly random but are set with probability).

I have tried

import random

random.randint(1,100)
select % above 50
like image 384
trenten Avatar asked Oct 09 '14 15:10

trenten


People also ask

How do you generate a random value from a list in Python?

Using random. randrange() to select random value from a list. random. randrange() method is used to generate a random number in a given range, we can specify the range to be 0 to the length of the list, and get the index, and then the corresponding value.


2 Answers

Try using a weighted list, like this:

import random
my_list = ['A'] * 5 + ['B'] * 5 + ['C'] * 90
random.choice(my_list)

See Python Weighted Random. To make it twice as likely that a number from 51 to 100 will be chosen instead a number from 1 to 50, do this:

import random

my_list = []

for i in range(1, 100):
    my_list.append(i)
    if i > 50:
        my_list.append(i)

print my_list
print 'Random (sort of) choice: %s' % random.choice(my_list)
like image 170
Joe Mornin Avatar answered Sep 25 '22 23:09

Joe Mornin


Use a non-uniform distribution such as the triangular distribution, set the mode equal to the range max, and cast to int or round it.

like image 23
pjs Avatar answered Sep 27 '22 23:09

pjs