Ver Fonte

improved random tests

Kajetan Johannes Hammerle há 3 anos atrás
pai
commit
d972dff595
3 ficheiros alterados com 21 adições e 14 exclusões
  1. 7 5
      tests/RandomTests.cpp
  2. 12 8
      utils/Random.cpp
  3. 2 1
      utils/Random.h

+ 7 - 5
tests/RandomTests.cpp

@@ -51,17 +51,19 @@ static void testFloatCoin(Test& test) {
     for(int i = 0; i < 1000000; i++) {
         c[r.nextFloat() < 0.5f]++;
     }
-    test.checkFloat(0.0f, (c[0] - c[1]) / 1000000.0f, 0.001f, "coin");
+    test.checkFloat(0.0f, (c[0] - c[1]) / 1000000.0f, 0.001f, "float coin");
 }
 
 static void testFloatDistribution(Test& test) {
     Random r(553);
-    Array<int, 100> c(0);
+    Array<int, 102> c(0);
     for(int i = 0; i < 1000000; i++) {
-        c[r.nextFloat() * c.getLength()]++;
+        c[r.nextFloat(1.0f, c.getLength() - 1)]++;
     }
-    for(int i = 0; i < c.getLength(); i++) {
-        test.checkFloat(0.01f, c[i] / 1000000.0f, 0.001f, "distribution");
+    test.checkEqual(0, c[0], "float distribution does not underflow");
+    test.checkEqual(0, c[c.getLength() - 1], "float distribution does not overflow");
+    for(int i = 1; i < c.getLength() - 1; i++) {
+        test.checkFloat(0.01f, c[i] / 1000000.0f, 0.001f, "float distribution");
     }
 }
 

+ 12 - 8
utils/Random.cpp

@@ -13,12 +13,6 @@ Random::Random(int seed) : index(0) {
 Random::Random() : Random(std::chrono::steady_clock::now().time_since_epoch().count()) {
 }
 
-float Random::nextFloat() {
-    static constexpr int bits = sizeof(int) * 6;
-    static constexpr int mask = (1 << bits) - 1;
-    return (next() & mask) * (1.0f / (1.0f + mask));
-}
-
 void Random::update() {
     static const int map[2] = {0, -1900031960};
     for(int i = 0; i < N - M; i++) {
@@ -41,6 +35,16 @@ int Random::next() {
     return r & static_cast<int> (-1u >> 1);
 }
 
-int Random::next(int min, int max) {
-    return min + next() % (max - min + 1);
+int Random::next(int min, int inclusiveMax) {
+    return min + next() % (inclusiveMax - min + 1);
+}
+
+float Random::nextFloat() {
+    static constexpr int bits = sizeof (int) * 6;
+    static constexpr int mask = (1 << bits) - 1;
+    return (next() & mask) * (1.0f / (1.0f + mask));
+}
+
+float Random::nextFloat(float min, float exclusiveMax) {
+    return min + nextFloat() * (exclusiveMax - min);
 }

+ 2 - 1
utils/Random.h

@@ -7,8 +7,9 @@ public:
     Random();
 
     int next();
-    int next(int min, int max);
+    int next(int min, int inclusiveMax);
     float nextFloat();
+    float nextFloat(float min, float exclusiveMax);
 
 private:
     constexpr static int N = 25;