【问题标题】:Sampling from a distribution with a margin of error从具有误差范围的分布中抽样
【发布时间】:2014-12-10 00:52:42
【问题描述】:

以下代码对加权随机分布进行抽样,作为模拟的一部分,代表 100k 个人可能采取的选项(例如:投票等)。

有两种可能的选项,权重分别为 30% 和 70%。

#include <iostream>
#include <random>

int main()
{
   int option0 = 30; //30%
   int option1 = 70; //30%

   std::vector<int> option({0,0});

   std::random_device rd;
   std::mt19937 gen(rd());
   std::discrete_distribution<> d({option0,option1});

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

   std::cout << "Option 0: " << option[0] << std::endl;
   std::cout << "Option 1: " << option[1] << std::endl;

   return 0;
}

问题:

如果上述百分比(权重)是通过对人口进行抽样调查得出的,并且确定margin of error5%

如何修改上述模拟以考虑到(也称为合并) 5% 的误差幅度?

【问题讨论】:

    标签: math random statistics distribution


    【解决方案1】:

    因为您确切地知道误差范围,所以您可以修改权重 随机生成的双精度数(介于 -5.0 和 5.0 之间),然后运行您建议的模拟。

    此函数将模拟所需的误差范围:

    void
    simulating_margin_of_error(std::mt19937 gen, double marginOfError,
                               int* option0, int* option1)
    {
        std::uniform_real_distribution<double>
            distribution(-marginOfError,marginOfError);
        double number = distribution(gen);
    
        *option0 += (int) number;
        *option1 += - (int) number;
    }
    

    您可以在此处包含它:

    [...]
    std::mt19937 gen(rd());
    simulating_margin_of_error(gen, 5.0, &option0, &option1);
    std::discrete_distribution<> d({option0, option1});
    [...]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-13
      • 1970-01-01
      • 1970-01-01
      • 2015-08-28
      • 1970-01-01
      • 1970-01-01
      • 2018-04-23
      • 1970-01-01
      相关资源
      最近更新 更多