Fix #3523: Fix CustomGlobalRandomEngine for R (#3781)

**Symptom** Apple Clang's implementation of `std::shuffle` expects doesn't work
correctly when it is run with the random bit generator for R package:
```cpp
CustomGlobalRandomEngine::result_type
CustomGlobalRandomEngine::operator()() {
  return static_cast<result_type>(
      std::floor(unif_rand() * CustomGlobalRandomEngine::max()));
}
```

Minimial reproduction of failure (compile using Apple Clang 10.0):
```cpp
std::vector<int> feature_set(100);
std::iota(feature_set.begin(), feature_set.end(), 0);
    // initialize with 0, 1, 2, 3, ..., 99
std::shuffle(feature_set.begin(), feature_set.end(), common::GlobalRandom());
    // This returns 0, 1, 2, ..., 99, so content didn't get shuffled at all!!!
```

Note that this bug is platform-dependent; it does not appear when GCC or
upstream LLVM Clang is used.

**Diagnosis** Apple Clang's `std::shuffle` expects 32-bit integer
inputs, whereas `CustomGlobalRandomEngine::operator()` produces 64-bit
integers.

**Fix** Have `CustomGlobalRandomEngine::operator()` produce 32-bit integers.

Closes #3523.
This commit is contained in:
Philip Hyunsu Cho
2018-10-15 09:39:13 -07:00
committed by GitHub
parent 4302fc4027
commit b38c636d05
2 changed files with 27 additions and 2 deletions

View File

@@ -33,14 +33,14 @@ using RandomEngine = std::mt19937;
class CustomGlobalRandomEngine {
public:
/*! \brief The result type */
typedef size_t result_type;
using result_type = uint32_t;
/*! \brief The minimum of random numbers generated */
inline static constexpr result_type min() {
return 0;
}
/*! \brief The maximum random numbers generated */
inline static constexpr result_type max() {
return std::numeric_limits<size_t>::max();
return std::numeric_limits<result_type>::max();
}
/*!
* \brief seed function, to be implemented