Skip to content

Commit a571690

Browse files
committed
Merge pull request #1818 from jawj/master
Prevent _.random returning max + 1 in rare cases
2 parents be486a2 + ea68517 commit a571690

File tree

1 file changed

+4
-1
lines changed

1 file changed

+4
-1
lines changed

underscore.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1203,12 +1203,15 @@
12031203
};
12041204

12051205
// Return a random integer between min and max (inclusive).
1206+
// Note the subtraction of 1e-16, to prevent a very occasional error where we'd
1207+
// return max + 1 due to rounding (see
1208+
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random)
12061209
_.random = function(min, max) {
12071210
if (max == null) {
12081211
max = min;
12091212
min = 0;
12101213
}
1211-
return min + Math.floor(Math.random() * (max - min + 1));
1214+
return min + Math.floor(Math.random() * (max - min + 1 - 1e-16));
12121215
};
12131216

12141217
// A (possibly faster) way to get the current timestamp as an integer.

0 commit comments

Comments
 (0)