PageRenderTime 46ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/src/Faker/Provider/Biased.php

http://github.com/fzaninotto/Faker
PHP | 64 lines | 25 code | 6 blank | 33 comment | 1 complexity | b3b4854b3f7fc9b94a227b36846cc397 MD5 | raw file
  1. <?php
  2. namespace Faker\Provider;
  3. class Biased extends Base
  4. {
  5. /**
  6. * Returns a biased integer between $min and $max (both inclusive).
  7. * The distribution depends on $function.
  8. *
  9. * The algorithm creates two doubles, x ∈ [0, 1], y ∈ [0, 1) and checks whether the
  10. * return value of $function for x is greater than or equal to y. If this is
  11. * the case the number is accepted and x is mapped to the appropriate integer
  12. * between $min and $max. Otherwise two new doubles are created until the pair
  13. * is accepted.
  14. *
  15. * @param integer $min Minimum value of the generated integers.
  16. * @param integer $max Maximum value of the generated integers.
  17. * @param callable $function A function mapping x ∈ [0, 1] onto a double ∈ [0, 1]
  18. * @return integer An integer between $min and $max.
  19. */
  20. public function biasedNumberBetween($min = 0, $max = 100, $function = 'sqrt')
  21. {
  22. do {
  23. $x = mt_rand() / mt_getrandmax();
  24. $y = mt_rand() / (mt_getrandmax() + 1);
  25. } while (call_user_func($function, $x) < $y);
  26. return (int) floor($x * ($max - $min + 1) + $min);
  27. }
  28. /**
  29. * 'unbiased' creates an unbiased distribution by giving
  30. * each value the same value of one.
  31. *
  32. * @return integer
  33. */
  34. protected static function unbiased()
  35. {
  36. return 1;
  37. }
  38. /**
  39. * 'linearLow' favors lower numbers. The probability decreases
  40. * in a linear fashion.
  41. *
  42. * @return integer
  43. */
  44. protected static function linearLow($x)
  45. {
  46. return 1 - $x;
  47. }
  48. /**
  49. * 'linearHigh' favors higher numbers. The probability increases
  50. * in a linear fashion.
  51. *
  52. * @return integer
  53. */
  54. protected static function linearHigh($x)
  55. {
  56. return $x;
  57. }
  58. }