Pregunta

I want to define a specific probability density function (pdf) for n numbers at C++ and then pick some of them later in my code.

my pdf is : P (x) = (1/logn) * f(x)^(-2)

f(x) has a deterministic number that is already determined for each x earlier in my code.

I prefer to use standard library function, since I should use my program in a computer cluster that using additional libraries such as boost more likely produces further issues in that cluster.

my initial code that I have found is:

  for(int x=1;x<n+1;x++){
    // I calculate all f(x) and therefore P(x) here
  }
  std::default_random_engine generator;
  std::discrete_distribution<int> distribution { .. not sure how to use P(x)s here .. };

  int prob[n]={};

  for (int i=0; i<n; ++i) {
    int number = distribution(generator);
    ++prob[number];
  }

Many thanks in advance.

¿Fue útil?

Solución

You can now construct vector with weights:

std::vector< double> weights( n);
for( int i = 0; i < n; ++i) {
  weights[i] = pdf( i + 1);
}

std::default_random_engine generator;
std::discrete_distribution<int> distribution( weights.begin(), weights.end()) ;

int prob[n]={};

for ( int i=0; i<n; ++i) {
  int number = distribution( generator);
  ++prob[number];
}

This will generate starting from 0, this is how discrete_distribution works, but you can assume with no loss of correctness that values are calculated for a range 1, ..., n (weights are calculated for 1, ..., n).

example

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top