Class: Random::Binomial

Inherits:
Object
  • Object
show all
Defined in:
ext/binomial.c

Instance Method Summary (collapse)

Constructor Details

- (Random::Binomial) initialize(rng, n, theta)

Returns a random sampler from a binomial distribution.

This sampler uses table plus square histgram method with Robin Hoot method. This method constructs a table for each distribution. If you once construct the table, you can draw a random sample fast for large n (n >= 40), but the cost of the table construction is expensive. Therefore, if you need to draw many samples from the same binomial distribution, you had better to use this class. Otherwise, you should use Random#binomial.

Parameters:

  • rng (Random)

    a random number generator

  • n (Integer)

    the number of trials (n > 0)

  • theta (Float)

    success probability (0 < theta < 1)



218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
# File 'ext/binomial.c', line 218

static VALUE binomial_initialize(VALUE self, VALUE rng, VALUE num, VALUE prob)
{
  binomial_t *bin;
  int n = NUM2INT(num);
  double theta = NUM2DBL(prob);

  check_binomial_params(n, theta, "Random::Binomial.new");
  
  rb_iv_set(self, "rng", rng);
  Data_Get_Struct(self, binomial_t, bin);
  bin->n = n;
  bin->theta = theta;
  bin->p = ALLOC_N(double, bin->n + 1);

  fill_binomial_table(bin);
  fill_binomial_T_VT_table(bin);
  
  return Qnil;
}

Instance Method Details

- (Integer) n

Returns the parameter n, the number of trials.

Returns:

  • (Integer)

    the parameter n



272
273
274
275
276
277
278
# File 'ext/binomial.c', line 272

static VALUE binomial_n(VALUE self)
{
  binomial_t *bin;
  Data_Get_Struct(self, binomial_t, bin);

  return INT2NUM(bin->n);
}

- (Integer) rand

Draws a sample from the binomimial distribution whose parameters are specified in Random::Binomial.new.

Returns:

  • (Integer)

    a random sample



244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
# File 'ext/binomial.c', line 244

static VALUE binomial_rand(VALUE self)
{
  VALUE rng = rb_iv_get(self, "rng");
  binomial_t *bin;
  uint32_t I0 = rb_random_int32(rng);
  uint32_t ILk;
  double U;
  int J;

  Data_Get_Struct(self, binomial_t, bin);
  
  ILk = I0 & MASK(bin->k);
  if (bin->T[ILk] >= 0)
    return INT2NUM(bin->T[ILk]);
  
  U = rb_random_real(rng);
  J = floor((bin->n + 1)*U);
  if (U < bin->V[J])
    return INT2NUM(J);
  else
    return INT2NUM(bin->K[J]);
}

- (Float) theta

Returns the parameter theta, the success probability.

Returns:

  • (Float)

    the parameter theta



285
286
287
288
289
290
291
# File 'ext/binomial.c', line 285

static VALUE binomial_theta(VALUE self)
{
  binomial_t *bin;
  Data_Get_Struct(self, binomial_t, bin);

  return DBL2NUM(bin->theta);
}