RandomTests.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #include "tests/RandomTests.h"
  2. #include "data/Array.h"
  3. #include "tests/Test.h"
  4. #include "utils/Random.h"
  5. static void testAverage(Test& test) {
  6. Random r(553);
  7. float sum = 0;
  8. for(int i = 0; i < 1000000; i++) {
  9. sum += r.next(2, 10);
  10. }
  11. sum /= 1000000.0f;
  12. test.checkFloat(6.0f, sum, 0.01f, "average");
  13. }
  14. static void testCoin(Test& test) {
  15. Random r(553);
  16. Array<int, 2> c(0);
  17. for(int i = 0; i < 1000000; i++) {
  18. c[r.next() & 1]++;
  19. }
  20. test.checkFloat(0.0f, (c[0] - c[1]) / 1000000.0f, 0.001f, "coin");
  21. }
  22. static void testDistribution(Test& test) {
  23. Random r(553);
  24. Array<int, 102> c(0);
  25. for(int i = 0; i < 1000000; i++) {
  26. c[r.next(1, c.getLength() - 2)]++;
  27. }
  28. test.checkEqual(0, c[0], "distribution does not underflow");
  29. test.checkEqual(0, c[c.getLength() - 1], "distribution does not overflow");
  30. for(int i = 1; i < c.getLength() - 1; i++) {
  31. test.checkFloat(0.01f, c[i] / 1000000.0f, 0.001f, "distribution");
  32. }
  33. }
  34. static void testFloatAverage(Test& test) {
  35. Random r(553);
  36. float sum = 0;
  37. for(int i = 0; i < 1000000; i++) {
  38. sum += r.nextFloat();
  39. }
  40. sum /= 1000000.0f;
  41. test.checkFloat(0.5f, sum, 0.001f, "float average");
  42. }
  43. static void testFloatCoin(Test& test) {
  44. Random r(553);
  45. Array<int, 2> c(0);
  46. for(int i = 0; i < 1000000; i++) {
  47. c[r.nextFloat() < 0.5f]++;
  48. }
  49. test.checkFloat(0.0f, (c[0] - c[1]) / 1000000.0f, 0.001f, "float coin");
  50. }
  51. static void testFloatDistribution(Test& test) {
  52. Random r(553);
  53. Array<int, 102> c(0);
  54. for(int i = 0; i < 1000000; i++) {
  55. c[r.nextFloat(1.0f, c.getLength() - 1)]++;
  56. }
  57. test.checkEqual(0, c[0], "float distribution does not underflow");
  58. test.checkEqual(0, c[c.getLength() - 1],
  59. "float distribution does not overflow");
  60. for(int i = 1; i < c.getLength() - 1; i++) {
  61. test.checkFloat(0.01f, c[i] / 1000000.0f, 0.001f, "float distribution");
  62. }
  63. }
  64. void RandomTests::test() {
  65. Test test("Random");
  66. testAverage(test);
  67. testCoin(test);
  68. testDistribution(test);
  69. testFloatAverage(test);
  70. testFloatCoin(test);
  71. testFloatDistribution(test);
  72. test.finalize();
  73. }