Math
Offers math related utility methods.
randomizer()
The randomizer()
method returns a NumericRandomizer
component - an adapter for PHP Random\Randomizer
.
$randomizer = Math::randomizer();
You can optionally specify what Engine
you wish to use:
use Aedart\Utils\Math;
use Random\Engine\Mt19937;
$randomizer = Math::randomizer(new Mt19937());
int()
The ìnt()
method returns a random number between provided $min
and $max
:
echo Math::randomizer()->int(1, 10); // 7
See Random\Randomizer::getInt()
for details.
nextInt()
Returns the next positive integer.
echo Math::randomizer()->nextInt(); // 4
See Random\Randomizer::nextInt()
for details.
float()
float()
method returns a uniformly selected float between provided $min
and $max
:
echo Math::randomizer()->float(1.3, 5.2); // 3.7874125015802
See Random\Randomizer::getFloat()
for details.
nextFloat()
Returns the next float.
echo Math::randomizer()->nextFloat(); // 0.087539659531495
See Random\Randomizer::nextFloat()
for details.
seed()
Generates a value that can be used for seeding the random number generator.
use Aedart\Utils\Math;
$seed = Math::seed();
mt_srand($seed);
applySeed()
A wrapper for PHP's mt_srand()
method, which seeds the Mersenne Twister Random Number Generator.
use Aedart\Utils\Math;
$seed = 123456;
$list = ['a', 'b', 'c', 'd'];
Math::applySeed($seed);
$resultA = $list[ array_rand($list, 1) ];
Math::applySeed($seed);
$resultB = $list[ array_rand($list, 1) ];
echo $resultA; // b
echo $resultB; // b
Seed mode
Use the 3rd argument to specify the seeding algorithm mode:
use Aedart\Utils\Math;
$seed = 123456;
$list = ['a', 'b', 'c', 'd'];
Math::applySeed($seed, MT_RAND_PHP);
$resultA = $list[ array_rand($list, 1) ];
// ...etc