True or false output based on a probability

后端 未结 4 509
梦毁少年i
梦毁少年i 2020-12-09 07:22

Is there a standard function for Python which outputs True or False probabilistically based on the input of a random number from 0 to 1?

example of what I mean:

相关标签:
4条回答
  • 2020-12-09 07:49
    import random
    
    def decision(probability):
        return random.random() < probability
    
    0 讨论(0)
  • 2020-12-09 07:52

    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).

    0 讨论(0)
  • 2020-12-09 07:53

    If you want to amass a lot of data, I would suggest using a map:

        from numpy import random as rn
        p = 0.15
        data = rn.random(100)
        final_data = list(map(lambda x: x < p, data))
    
    0 讨论(0)
  • 2020-12-09 08:07

    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.

    0 讨论(0)
提交回复
热议问题