Generating Skewed Random Numbers

Comments

A quick and dirty way to generate skewed random numbers from when I needed test data for a game.

Skewing random numbers with quadratics and exponentials

A quick way to skew random numbers towards 0, i.e. to make lower numbers more likely, is to raise the random numbers to a power - the higher the power, the higher the skew. To skew the other way, i.e. to make higher numbers more likely, just subract from 1

1
2
x^2      -> Math.pow( Math.random(), 2 );
1-x^2    -> 1 - Math.pow( Math.random(), 2 );

Or you could use an exponential for more drastic curves.

1
2
e^(4x-4) -> Math.pow( Math.E, 4 * Math.random() - 4 );
1-e^(-4x)-> 1-Math.pow( Math.E, -4 * Math.random() );

Obviously not the most efficient way of generating random numbers, but could be useful in certain occasions where performance is not an issue.

A basic class to generate skewed random numbers

This gist is a rough and ready class to test random numbers. It takes a map functions, generates 10 numbers, and pretty prints them to the console.

Here’s the output of a run. Not very conclusive, I have only printed 10 numbers because of space.

1
2
3
4
5
6
7
8
RND 0.075 - 0.339 - 0.363 - 0.434 - 0.435 - 0.563 - 0.669 - 0.739 - 0.808 - 0.874
RND 0.037 - 0.069 - 0.158 - 0.258 - 0.266 - 0.424 - 0.501 - 0.551 - 0.933 - 0.994
PW2 0.002 - 0.024 - 0.031 - 0.033 - 0.113 - 0.140 - 0.369 - 0.540 - 0.576 - 0.679
PW2 0.008 - 0.227 - 0.760 - 0.821 - 0.821 - 0.853 - 0.874 - 0.874 - 0.999 - 1.000
PW4 0.000 - 0.000 - 0.001 - 0.004 - 0.004 - 0.052 - 0.151 - 0.435 - 0.498 - 0.501
PW4 0.030 - 0.079 - 0.370 - 0.875 - 0.967 - 0.977 - 0.986 - 0.993 - 0.994 - 0.998
EXP 0.020 - 0.025 - 0.028 - 0.033 - 0.038 - 0.044 - 0.166 - 0.171 - 0.352 - 0.462
EXP 0.247 - 0.376 - 0.429 - 0.448 - 0.703 - 0.752 - 0.820 - 0.850 - 0.862 - 0.909

Visualizing distribution with Canvas

Just for a laugh (stop sniggering at the back), I thought I’d try some primitive HTML Canvas visualizations. The CodePen below runs the same code on 1000 sample points, and uses vertical lines to show their distribution.

Check out this Pen!

That’s all folks

Nothing too exciting.

Comments