From 197e189cdd288e7a11b427c3c18a30affea04d92 Mon Sep 17 00:00:00 2001 From: Ian Chen Date: Tue, 6 Aug 2024 16:40:19 -0700 Subject: [PATCH] Check for 0 stddev when generating a random number using normal distribution (#615) Signed-off-by: Ian Chen --- src/Rand.cc | 9 +++++++++ src/Rand_TEST.cc | 7 +++++++ 2 files changed, 16 insertions(+) diff --git a/src/Rand.cc b/src/Rand.cc index 0cb9b7b9f..b34dc40e4 100644 --- a/src/Rand.cc +++ b/src/Rand.cc @@ -25,6 +25,8 @@ #include #endif +#include + #include "gz/math/Rand.hh" using namespace gz; @@ -54,6 +56,10 @@ double Rand::DblUniform(double _min, double _max) ////////////////////////////////////////////////// double Rand::DblNormal(double _mean, double _sigma) { + if (equal(_sigma, 0.0, std::numeric_limits::epsilon())) + + return _mean; + NormalRealDist d(_mean, _sigma); return d(RandGenerator()); } @@ -69,6 +75,9 @@ int32_t Rand::IntUniform(int _min, int _max) ////////////////////////////////////////////////// int32_t Rand::IntNormal(int _mean, int _sigma) { + if (_sigma == 0) + return _mean; + NormalRealDist d(_mean, _sigma); return static_cast(d(RandGenerator())); diff --git a/src/Rand_TEST.cc b/src/Rand_TEST.cc index df31afbdc..ac8439fd9 100644 --- a/src/Rand_TEST.cc +++ b/src/Rand_TEST.cc @@ -51,6 +51,13 @@ TEST(RandTest, Rand) EXPECT_EQ(i, 9); EXPECT_NEAR(d, 3.00618, 1e-5); #endif + + // Test with sigma == 0 + d = math::Rand::DblNormal(2.0, 0.0); + i = math::Rand::IntNormal(10, 0); + + EXPECT_NEAR(2.0, d, 1e-6); + EXPECT_EQ(10, i); } #endif }