Search code examples
phprandomprobabilityprobability-theory

Calculating Odds Throttles in PHP


In PHP, if I build a factory inspection program with a conveyor belt where the popdown listbox on the form is 100% (inspect nothing -- let all go through) to 0% (inspect everything), what is the function to calculate when one of the widgets is due for inspection?

A little extra info -- the label says "Let [x%] widgets go through without inspection".

More than this, how can we test your algorithm to prove it's correct? For instance, a value of 100%, run 99999 times, should show no inspections. A value of 99%, run 99999 times, should maybe show one inspection in a blue moon if run repeatedly. A value of 0%, run 99999 times, should show all 99999 widgets being sent to inspection.

EDIT: A coworker says I'm getting odds and probability mixed up here. She thinks I'm describing probability?

Anyway, I tried this code as a test, but it doesn't do anything except at the 100, and 50 through 1 marks. However, the 1-49 act like the 50, while the 51 through 100 act like 100.

<?php

$nChance = @ $argv[1];
$nChance = intval($nChance);

for ($i = 1; $i <= 999999; $i++) {
  $nTest = rand(1,floor(100/$nChance));
  if (!($nTest == 1)) {
    die("INSPECT! i($i) rand($nTest) chance($nChance)\n");
  }
}

I then tried this variation and that failed too because it simply said INSPECT all the time.

<?php

$nChance = @ $argv[1];
$nChance = intval($nChance);

for ($i = 1; $i <= 999999; $i++) {
  $nTest = rand(0,100);
  if (!($nTest < $nChance)) {
    die("INSPECT! i($i) rand($nTest) chance($nChance)\n");
  }
}

Solution

  • $nChance = 5; // % chance of inspection
    $x       = 1; // number of seconds between products passing inspection point
    while ( isLineRunning() )
    {
        if( mt_rand(1,100) <= $nChance )
        {
            echo "INSPECT ITEM!";
        }
        sleep( $x );
    };
    

    this would check every 'x' seconds while the line is running.

    Your colleague is kind of correct but for your purposes you are making a decision based on whether a random number is less than or equal to (in this case) 5 which if truly random (which its not when generated like this) should deliver a 1 in 20 chance you select any given item.