Skip to content

Commit

Permalink
Avoid overflow. Fixes #8351.
Browse files Browse the repository at this point in the history
  • Loading branch information
swatanabe committed Mar 13, 2014
1 parent dbb7b3c commit c0a694e
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 0 deletions.
2 changes: 2 additions & 0 deletions include/boost/random/uniform_real_distribution.hpp
Expand Up @@ -65,6 +65,8 @@ T generate_uniform_real(
template<class Engine, class T>
inline T generate_uniform_real(Engine& eng, T min_value, T max_value)
{
if(max_value / 2 - min_value / 2 > (std::numeric_limits<T>::max)() / 2)
return 2 * generate_uniform_real(eng, min_value / 2, max_value / 2);

This comment has been minimized.

Copy link
@jzmaddock

jzmaddock Feb 28, 2015

Contributor

Unfortunately this fix breaks Boost.Multiprecision because for example min_value / 2 becomes an expression template and not a number. Adding a static_cast as in:

generate_uniform_real(eng, static_cast(min_value / 2), static_cast(max_value / 2));

Fixes things, and should be harmless for any other number type.

Longer term I need to look at the whole Multiprecision/Random interoperability issue in more detail. In principle are you open to more patches to address whatever issues there are? Plus some test cases to detect issues like this?

Thanks, John.

This comment has been minimized.

Copy link
@swatanabe

swatanabe via email Feb 28, 2015

Author Collaborator

This comment has been minimized.

Copy link
@jzmaddock

jzmaddock via email Feb 28, 2015

Contributor
typedef typename Engine::result_type base_result;
return generate_uniform_real(eng, min_value, max_value,
boost::is_integral<base_result>());
Expand Down
10 changes: 10 additions & 0 deletions test/test_uniform_real_distribution.cpp
Expand Up @@ -36,3 +36,13 @@
#define BOOST_RANDOM_TEST2_MAX 1.0

#include "test_distribution.ipp"

BOOST_AUTO_TEST_CASE(test_dbl_min_max) {
boost::random::minstd_rand rng;
double min = -(std::numeric_limits<double>::max)();
double max = (std::numeric_limits<double>::max)();
boost::random::uniform_real_distribution<double> dist(min, max);
double val = dist(rng);
BOOST_CHECK_GE(val, min);
BOOST_CHECK_LE(val, max);
}

0 comments on commit c0a694e

Please sign in to comment.