Why does this randomization method give distorted results?

I use two different methods of randomization, while one gives the results, the variance of which I expect, the other method gives the results, distorted and very consistent.

Methods:

function randomA() {
    var raw = Number((Math.random()+'').substr(2));
    return raw % NUM_OF_POSSIBLES;
}

function randomB() {
    var raw = Math.round(Math.random()*10000);
    return raw % NUM_OF_POSSIBLES;
}

When the NUM_OF_POSSIBLES = 2first method ( randomA()) leads to a fairly constant number of zeros (64%) and 36% of 1s. While radnomB()doing quite a lot of 50/50. If NUM_OF_POSSIBLES = 5, the first method is again distorted in a rather consistent way: 0: 10%, 1: 23%, 2: 22%, 3: 22%, 4: 23%, and the second gives about 20% to each result.

Here you can find the full code with several tests: jsfiddle

Why is the first method skewed, and also why a consistent skew?

+4
3

, , , , JavaScript . , . , . ( NUM_OF_POSSIBLES == 5 - 5s .) , .

, .

EDIT , , :

function randomA() {
    var raw = String(Math.random());
    raw = raw.substring(2, raw.length-1);
    return raw % NUM_OF_POSSIBLES;
}

, , , NUM_OF_POSSIBLES == 2 5.

+3

, , randomA , , java script poing 52 + 1 ( " " ). , , ,

Math.pow(2, 54) +1 
//18014398509481984
Math.pow(2, 54)  
//18014398509481984
Math.pow(2, 54)  -1
//18014398509481984

, 2 (- ).

, biniry, :

parseInt(Math.pow(2, 54) - 2).toString(2)
//"111111111111111111111111111111111111111111111111111110"
parseInt(Math.pow(2, 54) - 3).toString(2)
//"111111111111111111111111111111111111111111111111111100"
parseInt(Math.pow(2, 54) ).toString(2)
//"1000000000000000000000000000000000000000000000000000000"
parseInt(Math.pow(2, 54) -1).toString(2)
//"1000000000000000000000000000000000000000000000000000000"
+1

, Math.random() , , , 0.123 0.1235 "" .

, , , , 0.123 0.122999999999.

(% 2, % 5 ), .

, , , Javascript.

, - ...

+1

Source: https://habr.com/ru/post/1525275/


All Articles