RandomTests.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #include "tests/RandomTests.h"
  2. #include "tests/Test.h"
  3. #include "utils/Random.h"
  4. #include "utils/Array.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], "float distribution does not overflow");
  59. for(int i = 1; i < c.getLength() - 1; i++) {
  60. test.checkFloat(0.01f, c[i] / 1000000.0f, 0.001f, "float distribution");
  61. }
  62. }
  63. void RandomTests::test() {
  64. Test test("Random");
  65. testAverage(test);
  66. testCoin(test);
  67. testDistribution(test);
  68. testFloatAverage(test);
  69. testFloatCoin(test);
  70. testFloatDistribution(test);
  71. test.finalize();
  72. }