random has bug #921

Closed
faller opened this Issue Dec 26, 2012 · 2 comments

3 participants

@faller

in underscore
_.random = function(min, max) {
if (max == null) {
max = min;
min = 0;
}
return min + (0 | Math.random() * (max - min + 1));
};

return value may lte min, I found this by testing new Date().getTime() as args

the code (0 | Math.random() * (max - min + 1)) with
( 0 | 11531563792 ) returns -1353338096

@jvfl

Well, It's because of the bitwise operator (it only supports 32-bit integers). Don't know if it's a design decision in favor of speed( since that bitwise op is a bit faster than Math.floor), but using Math.floor instead of the bitwise op inside the function should do the job for you.

@faller

Klimetiel , you got the answer.

Number(11531563792).toString(2).length returns 34

lodash.js use Math.floor instead

@jdalton jdalton closed this in ae3cdd3 Dec 29, 2012
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment