具有特定比例的二进制随机数组? [英] Binary random array with a specific proportion of ones?

查看:27
本文介绍了具有特定比例的二进制随机数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

生成具有特定比例的随机数的零和一的有效方法(可能使用 Matlab 术语进行矢量化)是什么?特别是 Numpy?

由于我的情况是 1/3 的特殊情况,我的代码是:

将 numpy 导入为 npa=np.mod(np.multiply(np.random.randomintegers(0,2,size)),3)

但是,至少对于 K 和 N 是自然数的 K/N 情况,是否有任何内置函数可以更有效地处理这个问题?

解决方案

如果我正确理解你的问题,你可能会得到一些帮助 numpy.random.shuffle

<预><代码>>>>def rand_bin_array(K, N):arr = np.zeros(N)arr[:K] = 1np.random.shuffle(arr)返回 arr>>>rand_bin_array(5,15)数组([ 0., 1., 0., 1., 1., 1., 0., 0., 0., 1., 0., 0., 0.,0., 0.])

What is the efficient(probably vectorized with Matlab terminology) way to generate random number of zeros and ones with a specific proportion? Specially with Numpy?

As my case is special for 1/3, my code is:

import numpy as np 
a=np.mod(np.multiply(np.random.randomintegers(0,2,size)),3)

But is there any built-in function that could handle this more effeciently at least for the situation of K/N where K and N are natural numbers?

解决方案

If I understand your problem correctly, you might get some help with numpy.random.shuffle

>>> def rand_bin_array(K, N):
    arr = np.zeros(N)
    arr[:K]  = 1
    np.random.shuffle(arr)
    return arr

>>> rand_bin_array(5,15)
array([ 0.,  1.,  0.,  1.,  1.,  1.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,
        0.,  0.])

这篇关于具有特定比例的二进制随机数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆