1

How does one sample from a distribution in MathDotNet without having to cast to the specific distribution?

I have a distribution d which could be any random variable, being passed around as an IDistribution. Now, I wish to sample from it. I want to do this with having to do as few casts as possible on the actual distribution itself (I don't want a giant case statement with a ton of casts to really specific distribution types like Bernoulli, Normal, etc.

I have tried the following code, for an IDistribution d who is of type Bernoulli, with a mean of around 0.99:

Console.WriteLine("Mean is " + ((Bernoulli)d).Mean);
Console.WriteLine("Casted sample is " + ((Bernoulli)d).Sample());
Console.WriteLine("Sample is " + d.RandomSource.NextDouble());

The first print statement prints 0.99, as expected. The second print statement tends to return 1, as expected, since 99% of the time it should return 1. The third print statement seems to be giving me what looks like a uniform random variable between 0 or 1 (NB: It might not be uniform, that's just with a quick eyeball test on print statements, but it's definitely NOT Bernoulli with mean 0.99).

How can I sample generally from the appropriate distribution?

user650261
  • 2,115
  • 5
  • 24
  • 47

1 Answers1

0

This is what I am currently doing. I would like to avoid the if statement, but for now, this works. If someone has a better answer, it would be preferable:

if (distribution is IContinuousDistribution){
    value = (double)((IContinuousDistribution)distribution).Sample();

}else{
   value = (double)((IDiscreteDistribution)distribution).Sample();

}
user650261
  • 2,115
  • 5
  • 24
  • 47