BiasedTest.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. namespace Faker\Test\Provider;
  3. use Faker\Provider\Biased;
  4. use Faker\Generator;
  5. use PHPUnit\Framework\TestCase;
  6. class BiasedTest extends TestCase
  7. {
  8. const MAX = 10;
  9. const NUMBERS = 25000;
  10. protected $generator;
  11. protected $results = array();
  12. protected function setUp()
  13. {
  14. $this->generator = new Generator();
  15. $this->generator->addProvider(new Biased($this->generator));
  16. $this->results = array_fill(1, self::MAX, 0);
  17. }
  18. public function performFake($function)
  19. {
  20. for($i = 0; $i < self::NUMBERS; $i++) {
  21. $this->results[$this->generator->biasedNumberBetween(1, self::MAX, $function)]++;
  22. }
  23. }
  24. public function testUnbiased()
  25. {
  26. $this->performFake(array('\Faker\Provider\Biased', 'unbiased'));
  27. // assert that all numbers are near the expected unbiased value
  28. foreach ($this->results as $number => $amount) {
  29. // integral
  30. $assumed = (1 / self::MAX * $number) - (1 / self::MAX * ($number - 1));
  31. // calculate the fraction of the whole area
  32. $assumed /= 1;
  33. $this->assertGreaterThan(self::NUMBERS * $assumed * .95, $amount, "Value was more than 5 percent under the expected value");
  34. $this->assertLessThan(self::NUMBERS * $assumed * 1.05, $amount, "Value was more than 5 percent over the expected value");
  35. }
  36. }
  37. public function testLinearHigh()
  38. {
  39. $this->performFake(array('\Faker\Provider\Biased', 'linearHigh'));
  40. foreach ($this->results as $number => $amount) {
  41. // integral
  42. $assumed = 0.5 * pow(1 / self::MAX * $number, 2) - 0.5 * pow(1 / self::MAX * ($number - 1), 2);
  43. // calculate the fraction of the whole area
  44. $assumed /= pow(1, 2) * .5;
  45. $this->assertGreaterThan(self::NUMBERS * $assumed * .9, $amount, "Value was more than 10 percent under the expected value");
  46. $this->assertLessThan(self::NUMBERS * $assumed * 1.1, $amount, "Value was more than 10 percent over the expected value");
  47. }
  48. }
  49. public function testLinearLow()
  50. {
  51. $this->performFake(array('\Faker\Provider\Biased', 'linearLow'));
  52. foreach ($this->results as $number => $amount) {
  53. // integral
  54. $assumed = -0.5 * pow(1 / self::MAX * $number, 2) - -0.5 * pow(1 / self::MAX * ($number - 1), 2);
  55. // shift the graph up
  56. $assumed += 1 / self::MAX;
  57. // calculate the fraction of the whole area
  58. $assumed /= pow(1, 2) * .5;
  59. $this->assertGreaterThan(self::NUMBERS * $assumed * .9, $amount, "Value was more than 10 percent under the expected value");
  60. $this->assertLessThan(self::NUMBERS * $assumed * 1.1, $amount, "Value was more than 10 percent over the expected value");
  61. }
  62. }
  63. }