Skip to content

Commit

Permalink
Merge pull request #486 from amlalejini/fix-random-reset-seed
Browse files Browse the repository at this point in the history
Fix emp::Random ResetSeed
  • Loading branch information
amlalejini authored Aug 9, 2023
2 parents 79c4ffc + 4d49782 commit ae47837
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
4 changes: 4 additions & 0 deletions include/emp/math/Random.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,10 @@ namespace emp {

weyl_state *= 2; // Make sure starting state is even.

// Reset other internal state
value = 0;
expRV = 0.0;

Get(); // Prime the new sequence by skipping the first number.
}

Expand Down
47 changes: 46 additions & 1 deletion tests/math/Random.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ TEST_CASE("Test Random", "[math]")
REQUIRE(b2_result < 50);

emp::RandomStdAdaptor randomStd(rnd);
REQUIRE(randomStd(4) == 1);
REQUIRE(randomStd(4) == 3);

REQUIRE(rnd.GetRandGeometric(1) == 1);
REQUIRE(rnd.GetRandGeometric(0) == std::numeric_limits<uint32_t>::infinity());
Expand Down Expand Up @@ -295,3 +295,48 @@ TEST_CASE("Another Test random", "[math]")
REQUIRE(v.first + v.second == 0);
}
}

TEST_CASE("Calling ResetSeed should reset all generator internal state", "[math]") {

SECTION("Test internal 'value'") {
// Get Seed
emp::Random rnd(-1); // Initialize without a seed
rnd.ResetSeed(5);
REQUIRE(rnd.GetSeed() == 5);

emp::vector<int> sequence_a;
for (size_t i = 0; i < 10; ++i) {
sequence_a.emplace_back(rnd.GetInt(10000));
}

rnd.ResetSeed(5);
emp::vector<int> sequence_b;
for (size_t i = 0; i < 10; ++i) {
sequence_b.emplace_back(rnd.GetInt(10000));
}

// Tests internal 'value'
REQUIRE(sequence_a == sequence_b);
}

SECTION("Test internal expV") {
emp::Random rnd(10);
rnd.GetRandNormal(); // Adjusts expV with time-based seed generator

rnd.ResetSeed(4); // Should reset expV
emp::vector<double> norm_seq_a;
for (size_t i = 0; i < 1000; ++i) {
norm_seq_a.emplace_back(rnd.GetRandNormal());
}

rnd.ResetSeed(4);
emp::vector<double> norm_seq_b;
for (size_t i = 0; i < 1000; ++i) {
norm_seq_b.emplace_back(rnd.GetRandNormal());
}

// Tests internal expV
REQUIRE(norm_seq_a == norm_seq_b);
}

}

0 comments on commit ae47837

Please sign in to comment.