Skip to content

Commit

Permalink
Check for 0 stddev when generating a random number using normal distr…
Browse files Browse the repository at this point in the history
…ibution (#615)

Signed-off-by: Ian Chen <[email protected]>
  • Loading branch information
iche033 authored Aug 6, 2024
1 parent 0ebc06e commit 197e189
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/Rand.cc
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@
#include <unistd.h>
#endif

#include <limits>

#include "gz/math/Rand.hh"

using namespace gz;
Expand Down Expand Up @@ -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<double>::epsilon()))

return _mean;

NormalRealDist d(_mean, _sigma);
return d(RandGenerator());
}
Expand All @@ -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<int32_t>(d(RandGenerator()));
Expand Down
7 changes: 7 additions & 0 deletions src/Rand_TEST.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down

0 comments on commit 197e189

Please sign in to comment.