math-php icon indicating copy to clipboard operation
math-php copied to clipboard

Allow sampling from uniform and categorical distributions

Open balping opened this issue 1 year ago • 2 comments

Now you can sample from uniform and categorical discrete distributions by calling rand().

Examples:

$uniform = new Uniform(10, 20);
$random = $uniform->rand();


$categorical   = new Categorical(3, ['a' => 0.2, 'b' => 0.5, 'c' => 0.3]);
$random  = $categorical->rand(); // $random is 'a' or 'b' or 'c'

PS. I'm not sure why the static analysis is failing

balping avatar Dec 01 '24 00:12 balping

Coverage Status

coverage: 99.912% (-0.009%) from 99.921% when pulling 80d51f9958ad96fc374f6f7ae2d9a3c367e0f932 on balping:master into e587bfe3aadddfba0f3a40f49d2ed91132f30c5a on markrogoyski:master.

coveralls avatar Dec 01 '24 00:12 coveralls

Hi @balping,

Thank you for your interest in MathPHP, and thank you for the PR to add random functions to the Uniform and Categorical distributions.

The Uniform distribution random function looks good.

For the Categorical distribution, how about first defining a simple public cdf function on the distribution that returns the sum up to the point of the category selected. For order, how about just using the order of the categories as provided in the input array when constructing the distribution? The user can decide the order upon construction. Then, then rand function can make use of cdf internally. The cdf function itself could set a private parameter for storing all the cumulative sums.

How does that sound?

Thank you again for your PR! Mark

markrogoyski avatar Dec 02 '24 06:12 markrogoyski