Skip to content
This repository has been archived by the owner on Dec 11, 2020. It is now read-only.

Add biased/weighted “random” numbers #304

Closed
max-m opened this issue Apr 17, 2014 · 4 comments
Closed

Add biased/weighted “random” numbers #304

max-m opened this issue Apr 17, 2014 · 4 comments

Comments

@max-m
Copy link

max-m commented Apr 17, 2014

What about adding an generator for “weighted random numbers”?
For example a generator like this gamma “corrected” random number generator:

Author: bobince

/*
 * Generates a weighted random number
 *
 * Choose a continuous random number between 0..1
 * Raise to a power γ, to bias it. 1 is unweighted, lower gives more of the higher numbers and vice versa
 * Scale to desired range and round to integer
 *
 * @author bobince <http://stackoverflow.com/a/445363/1112384>
 */
public static function weightedRand($min, $max, $gamma) {
    $offset = $max - $min + 1;
    return floor($min + pow(lcg_value(), $gamma) * $offset);
}

Here is the probability distribution of calling weightedRand(1, 4, $gamma);.
May need some tweeking with values lower or equal to 0 though.

[kernel@~]php development/test.php 2.2
Gamma: 2.2
1: 53233 (53.233%)
2: 19662 (19.662%)
3: 14678 (14.678%)
4: 12427 (12.427%)
[kernel@~]php development/test.php 1.9
Gamma: 1.9
1: 48102 (48.102%)
2: 21317 (21.317%)
3: 16449 (16.449%)
4: 14132 (14.132%)
[kernel@~]php development/test.php 0
Gamma: 0
5: 100000 (100%)
[kernel@~]php development/test.php -.09
Gamma: -0.09
5: 91459 (91.459%)
6: 7433 (7.433%)
7: 901 (0.901%)
8: 155 (0.155%)
9: 35 (0.035%)
10: 8 (0.008%)
11: 5 (0.005%)
12: 3 (0.003%)
14: 1 (0.001%)

This might come in handy some times ^^

@Anahkiasen
Copy link

I would love this, when seeding fake data like friends on a social website, a lot of the time fake users have more fake friends than my testing account (which is sad I know).

@fzaninotto
Copy link
Owner

That's a good idea. It would be even better if there were several "distributions", just like tweens in animation. Maybe as an additional parameter?

randomNumber($from, $to, $distribution)

Where $distribution is "linear" by default, but can also take other values ("pow", "log", "gaussian", etc).

@TimWolla
Copy link
Contributor

TimWolla commented May 7, 2014

@fzaninotto I don't know when you want to release 1.4, but if I have enough time I might get this done for 1.4 as well. It looks like Rejection sampling does work very well for these kind of things.

@fzaninotto
Copy link
Owner

Fixed by #332

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants