I'm finding that RNG for Beta is not passing the chi-squared goodness of fit test. I am using the following code:
template <class RNG>
inline double
beta_rng(double alpha,
double beta,
RNG& rng1,
RNG& rng2) {
using boost::variate_generator;
using boost::random::gamma_distribution;
variate_generator<RNG&, gamma_distribution<> >
rng_gamma_alpha(rng1, gamma_distribution<>(alpha, 1.0));
variate_generator<RNG&, gamma_distribution<> >
rng_gamma_beta(rng2, gamma_distribution<>(beta, 1.0));
return rng_gamma_alpha() / (rng_gamma_alpha() + rng_gamma_beta());
}
TEST(ProbDistributionsBeta, doesFit) {
boost::random::mt19937 rng1, rng2;
int N = 10000;
int K = 5;
boost::math::beta_distribution<>dist (2.0,2.0);
boost::math::chi_squared mydist(K-1);
double loc[4];
for(int i = 1; i < K; i++)
loc[i - 1] = quantile(dist, 0.2 * i);
int count = 0;
int bin [5] = {0, 0, 0, 0, 0};
while (count < N) {
double a = stan::prob::beta_rng(2.0,2.0,rng1,rng2);
int i = 0;
while (i < K-1 && a > loc[i])
++i;
++bin[i];
count++;
}
double chi = 0;
double expect [5] = {N / K, N / K, N / K, N / K, N / K};
for(int j = 0; j < K; j++)
chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);
EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));
}
When I run the test, I get that the value of chi is 2120.29 which is not less than 33.3768 (qunatile(complement(mydist,1e-6))).
However, when I decrease N to 100 or less, the test passes..