dimanche 31 juillet 2016

coin flip experiment in C++ using std::rand() giving incorrect result

I'm trying to count the number of occurrences of the string HHHHHHTTTTTT in 1 million flips. For the coin flip, I'm using a simple std::rand() % 2. The code below. Mathematically, the expected answer is

(10^6 - 12 + 1) / 2^12 = 244

I got this result from a probability textbook. But my code is consistently getting only about half of that, i.e. around 122. Is this an issue with using std::rand() as a coin flip algorithm, or is there a bug in my code?

#include <iostream>
#include <cstdlib>
#include <vector>
#include <ctime>

using std::vector;

bool coin_flip(){
  return std::rand() % 2;
}

int count_string(int n, const vector<bool>& s){
  int k=0, res=0;
  for(int i=0; i<n; i++){
    if(coin_flip()==s[k]){
      k++; 
      if(k==s.size()){
        res++;
        k=0;
      }
    }else{
      k=0;
    } 
  }
  return res;
}

int main(){
  std::srand(std::time(0));

  vector<bool> v(12);
  const int a[12] = {1,1,1,1,1,1,0,0,0,0,0,0};
  for(int i=0; i<12; i++){
    v[i] = a[i];
  }

  std::cout << count_string(1000000, v) << '\n'; 
  return 0;
}




Aucun commentaire:

Enregistrer un commentaire