True or false output based on a probability
This video explains
True or false output based on a probability
--
Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 2 Looping
--
Chapters
00:00 Question
00:36 Accepted answer (Score 129)
00:46 Answer 2 (Score 3)
01:15 Answer 3 (Score 1)
01:34 Answer 4 (Score 0)
01:59 Thank you
--
Full question
https://stackoverflow.com/questions/5886...
Answer 2 links:
[PyProbs]: https://pypi.org/project/pyprobs/
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #scientificcomputing
#avk47
True or false output based on a probability
--
Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 2 Looping
--
Chapters
00:00 Question
00:36 Accepted answer (Score 129)
00:46 Answer 2 (Score 3)
01:15 Answer 3 (Score 1)
01:34 Answer 4 (Score 0)
01:59 Thank you
--
Full question
https://stackoverflow.com/questions/5886...
Answer 2 links:
[PyProbs]: https://pypi.org/project/pyprobs/
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #scientificcomputing
#avk47
ACCEPTED ANSWER
Score 145
import random
def decision(probability):
return random.random() < probability
ANSWER 2
Score 3
Given a function rand that returns a number between 0 and 1, you can define decision like this:
bool decision(float probability)
{
return rand()<probability;
}
Assuming that rand() returns a value in the range [0.0, 1.0) (so can output a 0.0, will never output a 1.0).
ANSWER 3
Score 1
Just use PyProbs library. It is very easy to use.
>>> from pyprobs import Probability as pr
>>>
>>> # You can pass float (i.e. 0.5, 0.157), int (i.e. 1, 0) or str (i.e. '50%', '3/11')
>>> pr.prob(50/100)
False
>>> pr.prob(50/100, num=5)
[False, False, False, True, False]
ANSWER 4
Score 0
I use this to generate a random boolean in python with a probability:
from random import randint
n=8 # inverse of probability
rand_bool=randint(0,n*n-1)%n==0
so to expand that :
def rand_bool(prob):
s=str(prob)
p=s.index('.')
d=10**(len(s)-p)
return randint(0,d*d-1)%d<int(s[p+1:])
I came up with this myself but it seems to work.