Change the probability of the pseudo-random values

,

The usual practice, when we need some test data, is to employ the pseudo-random built-in function RAND(). We usually use it to produce a random value in some range and it produces these values with the same probabilities. Sometimes we need more "realistic" data when some values are more probable than others are. In this cases we can still use RAND() function. The simple "trick" is to call it to produce a random number into the desired range and then use this value as a one of the boundaries of a new range. Run the script to see the sequence that it will produce. Notice that you can apply the "trick" more times to produce values with more "different" probabilities.

CREATE TABLE #mod20 (n int)
GO

DECLARE @mod20 int
DECLARE @i int

SELECT @i = 0

WHILE @i < 10000 BEGIN
    SELECT @mod20 = RAND()*20+1
    SELECT @mod20 = RAND()*@mod20+1

    INSERT #mod20 VALUES(@mod20)

    SELECT @i = @i+1
END

SELECT n, COUNT(*)
FROM #mod20 
GROUP BY n 
ORDER BY COUNT(*)
GO

DROP TABLE #mod20
GO

Rate

5 (1)

Share

Share

Rate

5 (1)