From bcb0386c991ac88e57124f7c6eddd01cae9624d5 Mon Sep 17 00:00:00 2001 From: Yixing Lao Date: Fri, 24 Jun 2022 01:22:20 -0700 Subject: [PATCH] move random int to cpp --- cpp/open3d/utility/Random.cpp | 19 +++++++++++++++++++ cpp/open3d/utility/Random.h | 13 +++++++------ 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/cpp/open3d/utility/Random.cpp b/cpp/open3d/utility/Random.cpp index e301bbd54c9..93b4fbc8ea9 100644 --- a/cpp/open3d/utility/Random.cpp +++ b/cpp/open3d/utility/Random.cpp @@ -26,6 +26,8 @@ #include "open3d/utility/Random.h" +#include "open3d/utility/Logging.h" + namespace open3d { namespace utility { @@ -47,5 +49,22 @@ RandomGlobalContext::RandomGlobalContext() { Seed(rd()); } +RandIntGenerator::RandIntGenerator(const int low, const int high) + : distribution_(low, high) { + if (low < 0) { + utility::LogError("low must be > 0, but got {}.", low); + } + if (low >= high) { + utility::LogError("low must be < high, but got low={} and high={}.", + low, high); + } +} + +int RandIntGenerator::operator()() { + std::lock_guard lock( + *RandomGlobalContext::GetInstance().GetMutex()); + return distribution_(*RandomGlobalContext::GetInstance().GetEngine()); +} + } // namespace utility } // namespace open3d diff --git a/cpp/open3d/utility/Random.h b/cpp/open3d/utility/Random.h index 31ac6c4fca2..0da6bbcbdbc 100644 --- a/cpp/open3d/utility/Random.h +++ b/cpp/open3d/utility/Random.h @@ -68,13 +68,14 @@ class RandomGlobalContext { /// from a uniform distribution class RandIntGenerator { public: - RandIntGenerator(const int min, const int max) : distribution_(min, max) {} + /// Generate uniformly distributed random integer from + /// [low, low + 1, ... high - 1]. + /// + /// \param low The lower bound (inclusive). \p low must be >= 0. + /// \param high The upper bound (exclusive). \p high must be > \p low. + RandIntGenerator(const int low, const int high); - int operator()() { - std::lock_guard lock( - *RandomGlobalContext::GetInstance().GetMutex()); - return distribution_(*RandomGlobalContext::GetInstance().GetEngine()); - } + int operator()(); protected: std::uniform_int_distribution distribution_;