Skip to content

Instantly share code, notes, and snippets.

@mahadirz
Last active March 5, 2020 03:39
Show Gist options
  • Save mahadirz/11acbfa28993166571c3137e7cdcfe85 to your computer and use it in GitHub Desktop.
Save mahadirz/11acbfa28993166571c3137e7cdcfe85 to your computer and use it in GitHub Desktop.
Web traffic allocation algorithm for A/B Test
<?php
/**
* @author Mahadir Ahmad
* http://madet.my
* Traffic Allocation Algorithm
*
*/
/**
* O(n) method of generating Binom(n,p) distributed random numbers
* Taken from https://github.com/gburtini/Probability-Distributions-for-PHP/blob/master/src/gburtini/Distributions/Binomial.php
*
*/
function draw($n, $p)
{
$x = 0;
for ($i = 0; $i < $n; $i++) {
if ((mt_rand() / mt_getrandmax()) < $p) {
$x = $x + 1;
}
}
return $x;
}
/**
* Use binomial random generator to draw 0 or 1
* based on specified percentage of traffic to receive
*
*/
function isSampleTraffic($percentage = 1)
{
return draw(1, $percentage) == 1;
}
function simulate($hits, $percentage)
{
$sampled_hits = [];
foreach ($hits as $val) {
if (isSampleTraffic($percentage)) {
//this traffic can then be tagged with variant A/B/C/etc
// and used to show the variant version of the test
array_push($sampled_hits, 1);
}
}
echo "End of the day result<br>";
echo $percentage * 100 . "% Traffic<br>";
echo "Sampled count: " . count($sampled_hits) . "<br>";
echo "Percentage of sampled: " . count($sampled_hits) / count($hits) * 100 . "%<br><br>";
}
// Simulation
//generate 10k hits
$hits = [];
for ($i = 0; $i < 10000; $i++) {
$hits[$i] = 1;
}
// 100% allocation
simulate($hits, 1);
// 50% allocation
simulate($hits, 0.5);
// 25% allocation
simulate($hits, 0.25);
// 75% allocation
simulate($hits, 0.75);
// 30% allocation
simulate($hits, 0.30);
// 15% allocation
simulate($hits, 0.15);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment