### Thread: Function which returns true with a given probability

1. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Apr 2007
Posts
3
Rep Power
0

#### Function which returns true with a given probability

I need to create a function which returns true with a given probability. For example:

foo(.1) returns true with probability .1

Could someone provide either a ruby implementation or a generic way to do this?
2. No Profile Picture
rebel with a cause
Devshed God 1st Plane (5500 - 5999 posts)

Join Date
May 2004
Location
The Batsh!t Crazy State.
Posts
5,817
Rep Power
3462
Code:
```public boolean foo(double probability) {
return true;
}```

Seriously, You've got to specify some more logical requirements than that.
3. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Apr 2007
Posts
3
Rep Power
0
I've said plenty. The technical term for what I have described is weighted random selection. In this case, the selection is between two elements: true and false. The probability p, given as an argument, is the weight assigned to true, and therefore the weight assigned to false is 1-p.

I ended up finding a Ruby implementation of weighted random selection that works for any number of elements; using this, I wrote my function.
4. Its one of those things you have to read twice. Trust me, he isn't usually so "out-of-it". Also, welcome to Dev Shed =D
5. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Apr 2007
Posts
3
Rep Power
0
Its one of those things you have to read twice.
Agreed. Also, I probably could have done better job explaining what I was looking for.

6. No Profile Picture
Contributing User
Devshed Regular (2000 - 2499 posts)

Join Date
Jul 2006
Posts
2,270
Rep Power
1737
Use a PRNG.

Say you take a probability out of 100. So for foo(.1), that's really like saying, I have a random number from 1-100. Is it less than 10? A standard PRNG available in most languages gives you a uniform distribution, so the probability is .1 that the number is less than 10. So look up creating random numbers in Ruby.

Generate random number within a range (something like 1-100, 1-1000). Check if random number is less than probability*range. If it is, return true, otherwise return false.