Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate skewed random numbers in Javascript?

Using Javascript, how can I generate random numbers that are skewed towards one end or the other of the distribution? Or ideally an point within the range?

For context: I'm creating a UI that has uses a grid of random grey squares. I'm generating the grey's RGB values using Math.random() but would like to be able to skew the greys to be on average darker or lighter while still having the full range from black to white represented.

(I think this is a similar question to Skewing java random number generation toward a certain number but I'm working with Javascript...)

Any help greatly appreciated.

like image 802
edeverett Avatar asked Dec 08 '22 23:12

edeverett


1 Answers

Raise Math.random() to a power to get a gamma curve - this changes the distribution between 0 and 1, but 0 and 1 stay constant endpoints.

var r= Math.pow(Math.random(), 2);
var colour= 'rgb('+r*255+', '+r*255+', '+r*255+')';

For gamma>1, you will get darker output; for 0<gamma<1 you get lighter. (Here, '2' gives you the x-squared curve; the equidistant lightness would be '0.5' for the square-root curve.)

like image 120
bobince Avatar answered Dec 28 '22 22:12

bobince