robier/probability-checker

概率检查器是一个简单的库,可以帮助您检查事件发生的概率。

v1.0.2 2024-05-23 23:47 UTC

This package is auto-updated.

Last update: 2024-09-24 00:50:15 UTC


README

codecov

ProbabilityChecker

这是一个非常简单的概率实现,可以用于A/B测试。如果您想在20%的请求上运行某个功能。这个工具非常适合您,因为您不需要定义总的请求数量。

如果您将参数设置为0,它将始终返回false,如果您将参数设置为100,它将始终返回true。介于两者之间的值将接近您提供的数字。

注意:此方法不是精确的,而是近似值,因此如果您想要20%,您可能会得到21%、23%或18%,但最终它将接近20%(请求数量越多,百分比越准确)。

安装

此库可以通过composer安装

composer require robier/probability-checker

示例用法

<?php

$probability = new \Robier\ProbabilityChecker(30);

$skipped = 0;
$executed = 0;
for($i = 0; $i < 1000000; $i++) {
    if ($probability->roll()) {
        $executed++;
    } else {
    	$skipped++;
    }
}

$percentageAtTheEndSkipped = round($skipped / ($executed + $skipped), 6) * 100;
$percentageAtTheEndExecuted = round(100 - $percentageAtTheEndSkipped, 6);

echo "Executed $executed and Skipped $skipped \n";
echo "Executed $percentageAtTheEndExecuted% and Skipped $percentageAtTheEndSkipped%";

第一次运行

Skipped 699978 and Executed 300022 
Skipped 69.9978% and Executed 30.0022%

第二次运行

Skipped 699813 and Executed 300187 
Skipped 69.9813% and Executed 30.0187%

第三次运行

Skipped 700351 and Executed 299649 
Skipped 70.0351% and Executed 29.9649%

从这些结果中,您可以看到百分比不是精确的,但接近我们定义的30%。

方法

我们在类中有几个方法

本地开发

要本地运行测试,您可以使用提供的Docker设置。只需运行

docker/build

以构建镜像,然后运行

docker/run composer test

以运行测试。如果您想运行带有覆盖率测试,可以运行

docker/run composer test:coverage