C ++-生成具有可配置平均值"1s到0s"的随机位集的有效方法.比率 [英] C++ - Efficient way to generate random bitset with configurable mean "1s to 0s" ratio

查看:79
本文介绍了C ++-生成具有可配置平均值"1s到0s"的随机位集的有效方法.比率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种高效的方法来生成设定长度的随机std::bitset.我还希望能够影响结果中出现1的概率,因此,如果将概率值设置得足够低,则所有结果中只有一小部分甚至会包含1,但是仍然有可能(但极不可能)导致所有1.它将用于大量计算的应用程序,因此欢迎进行所有可能的优化.

I'm looking for a highly efficient way to generate random std::bitset of set length. I'd also like to be able to influence the probability of 1s appearing in the result, so if the probability value is set low enough, only a small percentage of all the results will even contain a 1, but it's still possible (but very unlikely) to result in all 1s. It's going to be used in a very computation-heavy application, so every possible optimization is welcome.

推荐答案

Bernoulli发行版是单个实验中1或0的概率分布.许多这样的分布式变量的总和

Bernoulli distribution is a probability distribution of 1 or 0 in a single experiment. A sum of many such distributed variables

给出一个以均值 n * p 分布的变量(二项式分布).因此,通过取由 p 给出的概率为 1 n 伯努利分布位,我们得到了大小为 n 的位集,并且 np 位平均设置为 1 .当然,如果这不能提供足够的效率,这只是下一步优化的起点.

gives a variable distributed with mean n*p (binomial distribution). So by taking n bernoulli distributed bits with probability of 1 given by p we get a bitset of size n and np bits set to 1 on average. Of course this is just a starting point to optimize next if the efficiency this offers is not enough.

#include <iostream>
#include <random>
#include <bitset>

template< size_t size>
typename std::bitset<size> random_bitset( double p = 0.5) {

    typename std::bitset<size> bits;
    std::random_device rd;
    std::mt19937 gen( rd());
    std::bernoulli_distribution d( p);

    for( int n = 0; n < size; ++n) {
        bits[ n] = d( gen);
    }

    return bits;
}

int main()
{
    for( int n = 0; n < 10; ++n) {
        std::cout << random_bitset<10>( 0.25) << std::endl;
    }
}

结果:

1010101001

1010101001

0001000000

0001000000

1000000000

1000000000

0110010000

0110010000

1000000000

1000000000

0000110100

0000110100

0001000000

0001000000

0000000000

0000000000

1000010000

1000010000

0101010000

0101010000

http://ideone.com/p29Pbz

这篇关于C ++-生成具有可配置平均值"1s到0s"的随机位集的有效方法.比率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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