jsrsasign
jsrsasign copied to clipboard
getBigRandom() is incorrect
this.getBigRandom = function (limit) {
return new BigInteger(limit.bitLength(), rng)
.mod(limit.subtract(BigInteger.ONE))
.add(BigInteger.ONE)
;
};
The above will unfairly privilege low numbers at the expense of high numbers. The initial BigInteger object is equally likely to be any number with the same bit length as “limit”. The modulo operation, then, makes for at least two separate ways by which the result of the operation can be a low number, while leaving only one path for the highest.
Example:
var r_int = Math.floor( 10 * Math.random() );
var r_int2 = r_int % 8;
r_int is equally likely to be any of the integers 0 to 9, inclusive; i.e., each integer has a 0.1 probability.
r_int2, however, has a .2 probability of being 0 and a .2 probability of being 1, while the probability of other possible r_int2 values is still 0.1.
@FGasper Mayby I just don't understand your example, but with those two lines you will always get a number less than 10, right? So why do you write about getting greater than 10?
@Ruffio Sorry, that was a bad example before. I’ve updated it to be (hopefully) clearer.
@FGasper do you have an idea of a 'correct' implementation of 'getBigRandom'? This is a little over my head... :-(
What is getBigRandom’s exact purpose? It seems to exclude 0 as a return value; is that by design?
A more-correct implementation would be to discard any random values that are greater than the maximum value we’d want to return.
Maybe something like:
this.getBigRandom = function (limit) {
var limit_minus_1 = limit.subtract(BigInteger.ONE);
while (1) {
var int = new BigInteger(limit.bitLength(), rng);
if (int.lessThan( limit_minus_1 )) { // not sure if this exists
return int.add(BigInteger.ONE);
}
}
};
Sorry for the untested-ness … hopefully later I can flesh it out a bit more.
@kjur is this bias of probability by intend or accidental? Should it be changed?
@kjur is this bias of probability by intend or accidental? Should it be changed?
@kjur is this bias of probability by intend or accidental? Should it be changed?
@kjur is this bias of probability by intend or accidental? Should it be changed?
@kjur what do you think?