Skip to content

Commit

Permalink
Fix Lua PcgRandom
Browse files Browse the repository at this point in the history
Before, this lua code led to a crash:

local pcg = PcgRandom(42)
local value = pcg:next()

This was because if you called s32 PcgRandom::range(min, max) with the
minimum and maximum possible values for s32 integers (which the lua
binding code did), u32 PcgRandom::range(bound) got called with 0 as the
bound. The bound however is one above the maximum value, so 0 is a "special"
value to pass to this function. This commit fixes the lua crash by
assigning the RNG's full range to the bound 0, which is also fits to the
"maximum is bound - 1" principle, as (u32)-1 is the maximum value in the
u32 range.
  • Loading branch information
est31 committed Aug 12, 2015
1 parent f0b3252 commit 738fbc6
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/noise.cpp
Expand Up @@ -90,6 +90,9 @@ u32 PcgRandom::next()

u32 PcgRandom::range(u32 bound)
{
// If the bound is 0, we cover the whole RNG's range
if (bound == 0)
return next();
/*
If the bound is not a multiple of the RNG's range, it may cause bias,
e.g. a RNG has a range from 0 to 3 and we take want a number 0 to 2.
Expand Down
3 changes: 3 additions & 0 deletions src/unittest/test_random.cpp
Expand Up @@ -101,6 +101,9 @@ void TestRandom::testPcgRandomRange()

EXCEPTION_CHECK(PrngException, pr.range(5, 1));

// Regression test for bug 3027
pr.range(pr.RANDOM_MIN, pr.RANDOM_MAX);

for (u32 i = 0; i != 32768; i++) {
int min = (pr.next() % 3000) - 500;
int max = (pr.next() % 3000) - 500;
Expand Down

0 comments on commit 738fbc6

Please sign in to comment.