Generate random array of 0 and 1 with a specific ratio

后端 未结 4 2144
孤城傲影
孤城傲影 2021-02-19 06:09

I want to generate a random array of size N which only contains 0 and 1, I want my array to have some ratio between 0 and 1. For example, 90% of the array be 1 and the remainin

4条回答
  •  难免孤独
    2021-02-19 06:41

    Its difficult to get an exact count but you can get approximate answer by assuming that random.random returns a uniform distribution. This is strictly not the case, but is only approximately true. If you have a truly uniform distribution then it is possible. You can try something like the following:

    In [33]: p = random.random(10000)
    In [34]: p[p <= 0.1] = 0
    In [35]: p[p > 0] = 1
    In [36]: sum(p == 0)
    Out[36]: 997
    In [37]: sum(p == 1)
    Out[37]: 9003
    

    Hope this helps ...

提交回复
热议问题