Commit 8365bf68 authored by Davis King's avatar Davis King

Added get_integer() and get_integer_in_range() to dlib::rand.

parent 178f4205
......@@ -146,6 +146,35 @@ namespace dlib
return begin + get_random_double()*(end-begin);
}
long long get_integer_in_range(
long long begin,
long long end
)
{
DLIB_ASSERT(begin <= end);
if (begin == end)
return begin;
auto r = get_random_64bit_number();
const auto limit = std::numeric_limits<decltype(r)>::max();
const auto range = end-begin;
// Use rejection sampling to remove the biased sampling you would get with
// the naive get_random_64bit_number()%range sampling.
while(r >= (limit/range)*range)
r = get_random_64bit_number();
return begin + static_cast<long long>(r%range);
}
long long get_integer(
long long end
)
{
DLIB_ASSERT(end >= 0);
return get_integer_in_range(0,end);
}
double get_random_double (
)
{
......
......@@ -149,6 +149,28 @@ namespace dlib
- returns begin
!*/
long long get_integer_in_range(
long long begin,
long long end
);
/*!
requires
- begin <= end
ensures
- returns a random integer selected from the range: begin <= N < end
The integer is selected uniformly at random.
!*/
long long get_integer(
long long end
);
/*!
requires
- 0 <= end
ensures
- returns get_integer_in_range(0,end)
!*/
double get_random_gaussian (
);
/*!
......
......@@ -381,6 +381,32 @@ namespace
DLIB_TEST(std::abs(max_val - 1.0) < 0.001);
}
void test_get_integer()
{
print_spinner();
dlib::rand rnd;
int big = 0;
int small = 0;
const long long maxval = (((unsigned long long)1)<<62) + (((unsigned long long)1)<<61);
for (int i = 0; i < 10000000; ++i)
{
if (rnd.get_integer(maxval) > maxval/2)
++big;
else
++small;
}
// make sure there isn't any funny bias
DLIB_TEST(std::abs(big/(double)small - 1) < 0.001);
cout << big/(double)small << endl;
}
class rand_tester : public tester
{
public:
......@@ -401,6 +427,7 @@ namespace
test_normal_numbers(rnd);
test_gaussian_random_hash();
test_uniform_random_hash();
test_get_integer();
}
} a;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment