Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix two big bugs in Normal #31

Merged
merged 1 commit into from
May 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions cxx/distributions/normal.hh
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ class Normal : public Distribution<double> {
// We use Welford's algorithm for computing the mean and variance
// of streaming data in a numerically stable way. See Knuth's
// Art of Computer Programming vol. 2, 3rd edition, page 232.
int mean = 0; // Mean of observed values
int var = 0; // Variance of observed values
double mean = 0.0; // Mean of observed values
double var = 0.0; // Variance of observed values

std::mt19937 *prng;

Expand All @@ -51,6 +51,11 @@ class Normal : public Distribution<double> {
void unincorporate(const double &x) {
int old_N = N;
--N;
if (N == 0) {
mean = 0.0;
var = 0.0;
return;
}
double old_mean = mean;
mean = (mean * old_N - x) / N;
var -= (x - mean) * (x - old_mean);
Expand Down
15 changes: 13 additions & 2 deletions cxx/distributions/normal_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,19 @@ BOOST_AUTO_TEST_CASE(simple) {
nd.incorporate(7.0);
nd.unincorporate(-2.0);

BOOST_TEST(nd.logp(6.0) == -3.1331256657870137, tt::tolerance(1e-6));
BOOST_TEST(nd.logp_score() == -4.7494000141508543, tt::tolerance(1e-6));
BOOST_TEST(nd.logp(6.0) == -2.7673076255063034, tt::tolerance(1e-6));
BOOST_TEST(nd.logp_score() == -4.7299819282937534, tt::tolerance(1e-6));
}

BOOST_AUTO_TEST_CASE(no_nan_after_incorporate_unincorporate) {
std::mt19937 prng;
Normal nd(&prng);

nd.incorporate(10.0);
nd.unincorporate(10.0);

BOOST_TEST(!std::isnan(nd.mean));
BOOST_TEST(!std::isnan(nd.var));
}

BOOST_AUTO_TEST_CASE(logp_before_incorporate) {
Expand Down
Loading