RandomTests.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 += static_cast<float>(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, static_cast<float>(c[0] - c[1]) / 1000000.0f, 0.001f,
  21. "coin");
  22. }
  23. static void testDistribution(Test& test) {
  24. Random r(553);
  25. Array<int, 102> c(0);
  26. for(int i = 0; i < 1000000; i++) {
  27. c[r.next(1, c.getLength() - 2)]++;
  28. }
  29. test.checkEqual(0, c[0], "distribution does not underflow");
  30. test.checkEqual(0, c[c.getLength() - 1], "distribution does not overflow");
  31. for(int i = 1; i < c.getLength() - 1; i++) {
  32. test.checkFloat(0.01f, static_cast<float>(c[i]) / 1000000.0f, 0.001f,
  33. "distribution");
  34. }
  35. }
  36. static void testFloatAverage(Test& test) {
  37. Random r(553);
  38. float sum = 0;
  39. for(int i = 0; i < 1000000; i++) {
  40. sum += r.nextFloat();
  41. }
  42. sum /= 1000000.0f;
  43. test.checkFloat(0.5f, sum, 0.001f, "float average");
  44. }
  45. static void testFloatCoin(Test& test) {
  46. Random r(553);
  47. Array<int, 2> c(0);
  48. for(int i = 0; i < 1000000; i++) {
  49. c[r.nextFloat() < 0.5f]++;
  50. }
  51. test.checkFloat(0.0f, static_cast<float>(c[0] - c[1]) / 1000000.0f, 0.001f,
  52. "float coin");
  53. }
  54. static void testFloatDistribution(Test& test) {
  55. Random r(553);
  56. Array<int, 102> c(0);
  57. for(int i = 0; i < 1000000; i++) {
  58. c[static_cast<int>(r.nextFloat(1.0f, c.getLength() - 1))]++;
  59. }
  60. test.checkEqual(0, c[0], "float distribution does not underflow");
  61. test.checkEqual(0, c[c.getLength() - 1],
  62. "float distribution does not overflow");
  63. for(int i = 1; i < c.getLength() - 1; i++) {
  64. test.checkFloat(0.01f, static_cast<float>(c[i]) / 1000000.0f, 0.001f,
  65. "float distribution");
  66. }
  67. }
  68. void RandomTests::test() {
  69. Test test("Random");
  70. testAverage(test);
  71. testCoin(test);
  72. testDistribution(test);
  73. testFloatAverage(test);
  74. testFloatCoin(test);
  75. testFloatDistribution(test);
  76. test.finalize();
  77. }