0

If I wanted to create a survey that displays the gender of your future babies with counting the ratio of having a male to female is 1.05 to 1. Assuming that each couple will get one baby only. How can I do that in php?

rand (0,1); will generate a random number (either 1 or 0). which can represent the gender. But, how can the ratio be applied as a probability in getting that number?

I know the ratio is very close, and maybe applying the ratio to my function will not effect the outcome at all. but I am doing this to educate myself so, give me an example of how this can be done.

syrkull
  • 2,295
  • 4
  • 35
  • 68
  • 5
    Choose between `rand(1, 205)`. If the value is <= 105, it's a male, > 105 is a female. – Michael Berkowski Mar 14 '13 at 18:11
  • @MichaelBerkowski nice. but still looking for other ways to find the ratio. please do not put your answer as a comment ^^" – syrkull Mar 14 '13 at 18:13
  • 2
    Think of it as though you have two boxes. One is slightly larger than the other. You throw a ball up into the air, its likelihood of landing in either box (in a vacuum of course) is related directly to the size of the box. – Michael Berkowski Mar 14 '13 at 18:13
  • .. Maybe blindfolded pin-the-tail-on-the-donkey is a better analogy than a ball... The idea is that you choose randomly between the sum of all your possible partitions, and simply assign the result to a partition range which you have predetermined. – Michael Berkowski Mar 14 '13 at 18:16

2 Answers2

2

as per @Michael Berkowski's comment:

/**
 * Generate random baby gender adjusted by ratio male to female 1.05:1
 *
 * @return
 *   TRUE if male or FALSE if female
 */
function is_random_male() {
    return rand(1, 205) <= 105;
}

echo is_random_male() ? 'male' : 'female';
Geo
  • 12,666
  • 4
  • 40
  • 55
1

1.05 to 1 is equivalent to:

  • Male % = (1 / 2.05) * 100 % = 48,78.. %
  • Female % = (1.05 / 2.05) * 100 % = 51.22.. %

Now depending on the degree of accuracy needed, you can do the following algorithm:

$rnd = rand(0,100);
if ($rnd < 48 ) {
    //male
}
else {
    //female
}

If you want even more accuracy:

$rnd = rand(0,10000);
if ($rnd < 4878 ) {
    //male
}
else {
    //female
}
Majid Laissi
  • 19,188
  • 19
  • 68
  • 105