472,992 Members | 3,171 Online

# Weighted randomness

1
Hey

I am trying to figure out a very simple code to do some weighted randomness.

I have two values, and I have to randomly pick among them on each iteration.
But I need, let's say, the first value to be picked on 60% of the cases, and the second value to be picked on 40% of the cases.

Anyone can write me some code or even pseudo code to do that?

I know it is simple, I learned it one day in my life, but right now I'm blank!

Thank u a lot
Daniel
Jul 10 '07 #1
4 1599
bartonc
6,596 Expert 4TB
Hey

I am trying to figure out a very simple code to do some weighted randomness.

I have two values, and I have to randomly pick among them on each iteration.
But I need, let's say, the first value to be picked on 60% of the cases, and the second value to be picked on 40% of the cases.

Anyone can write me some code or even pseudo code to do that?

I know it is simple, I learned it one day in my life, but right now I'm blank!

Thank u a lot
Daniel
I'm more of a mechanic than a mathematician (gui & device interfaces), but there sure are a lot of interesting looking functions with names like paretovariate in the random module. One of them has just gotta do what you're look for.
Jul 10 '07 #2
dmr
4
Here's an ugly way to do it: create a list of ten with 6 of one value and 4 of another, than randomly access the list.
Expand|Select|Wrap|Line Numbers
1. import random
2. import math
3.
4. s = [6,6,6,6,6,6,4,4,4,4]
5.
6. for i in range(1,100):
7.   print s[ int( math.floor( random.random() * 10) ) ]
8.
Aug 2 '07 #3
ilikepython
844 Expert 512MB
Here's an ugly way to do it: create a list of ten with 6 of one value and 4 of another, than randomly access the list.
Expand|Select|Wrap|Line Numbers
1. import random
2. import math
3.
4. s = [6,6,6,6,6,6,4,4,4,4]
5.
6. for i in range(1,100):
7.   print s[ int( math.floor( random.random() * 10) ) ]
8.
Just a little note: you don't need all that math to get a value from 1 to ten. Just do this:
Expand|Select|Wrap|Line Numbers
1. print s[random.randint(0, 9)]
2.
No biggie :)
Aug 2 '07 #4
dmr
4
Thanks, I don't know how I missed that. I've just started playing with Python and will remember it.
Aug 3 '07 #5