Skip to main content
Stack Overflow
  1. About
  2. For Teams

Timeline for Generating random whole numbers in JavaScript in a specific range

Current License: CC BY-SA 4.0

58 events
when toggle format what by license comment
Aug 18, 2024 at 17:18 comment added LΞИIИ What program do you use to explain with those characters?
Nov 30, 2022 at 17:41 history edited pgSystemTester CC BY-SA 4.0
Improved bracket appearance Math.Floor() example and clarified max+1 is excluded. Removed min+2.
Nov 30, 2022 at 16:32 comment added Aleksandar Further, no more than does not mean below. Why would minimum be included but not maximum, then, even minimum has to be excluded if we go by the logic: Exclude the min & max limits and keep the values between them. Examples: #2: getRandom(2,3) ALWAYS returns 2 - that is a wrong logic, it isn't handling the max-range. A max-range is the included max-limit. && #1: getRandom(2,2) returns 2 how is that for a max-limit that has to be excluded? And what if we excluded both limits:min2 is not allowed & max2 is not allowed? They're allowed limits!
Nov 30, 2022 at 15:52 comment added Aleksandar The first code example is wrong as it NEVER returns the MAX range, and the second example has unnecessary Math.ceil & Math.floor on the arguments when instead you can just WRAP them up in a Math.floor. I checked Mozilla docs and it's still not updated "Getting random number between two value" is INCORRECT ~> Why is the MAX excluded? - It shouldn't be! If you are allowed to take BETWEEN 2 and 5 apples: then you MUST take at minimum(at least) 2 & at maximum(no more than) 5 apples.
Oct 4, 2022 at 16:23 history edited Peter Mortensen CC BY-SA 4.0
Fixed the weird syntax highlighting (as a result, the diff looks more extensive than it really is - use view "Side-by-side Markdown" to compare).
Sep 15, 2021 at 15:29 comment added Ryan Griggs THANK YOU for adding the .floor() and .ceil() functions to the min and max values! I had omitted these, and was inadvertently passing strings to the function. It turns out "6" is not the same as 6, and it yields some maddening results! Adding floor and ceil ensure the inputs are actual numbers before performing the calculation, thus yielding the expected results.
May 29, 2021 at 4:06 history rollback user229044
Rollback to Revision 10
May 29, 2021 at 0:34 history edited dthree CC BY-SA 4.0
Added comparison.
Oct 26, 2020 at 15:05 comment added Fattie it's incredibly bad form to have inclusive on the end of an int returning function. random int functions are ALWAYS exclusive on the end. (Since computers count from 0 to 9, not 1 to 10.) if you do have a inclusive-on-the-end random into function, you MUST include "inclusive" in the name of the function. this is universal in all languages, APIs, OS, etc.
Aug 25, 2020 at 4:48 comment added Denis Giffeler With Crypto-Safe random routine: function myRand(from, to) { let row = new Uint32Array(1); window.crypto.getRandomValues(row); return row[0] % (to - from + 1) + from; }
May 6, 2020 at 18:47 comment added user3533413 That's why we add min back after everything gets resolved in Math.floor().
May 6, 2020 at 18:39 comment added user3533413 Continued from above: We take the floor of the result, and this gives us a random number within the size of the whole number list we desire, but we don't want a number between 0 and 34, we want -22 of that, which is -22 and 12.
May 6, 2020 at 18:37 comment added user3533413 For anyone having a hard time understanding this, write it on a piece of paper and plug in sample numbers and see what happens. In the getRandomInt() function, the interesting part is (max - min + 1). Take any arbitrary sequence of whole numbers from a to b. You can count the number of items in the sequence using b - a + 1. For example if you chose -12 for min and 22 for max, the number of whole numbers n where -12 <= n <= 22 is 22 - (-12) + 1 == 35. We choose a random number between 0 inclusive and 1 exclusive and multiply it by 35.
Apr 13, 2019 at 9:01 history edited micnic CC BY-SA 4.0
update link to MDN to avoid redirect
Jan 9, 2019 at 9:35 comment added user130496 If the question is how to generate whole numbers in a specific range, the first snippet posted should do exactly that. Now it generates floats instead. Just my 2 cents.
S Nov 14, 2018 at 18:02 history suggested alienriver49 CC BY-SA 4.0
Updated with latest MDN web docs example which will handle a non-integer min and / or max.
Nov 14, 2018 at 17:46 review Suggested edits
S Nov 14, 2018 at 18:02
Feb 7, 2018 at 9:23 comment added Ivan Reznikov Consider the fact that on the borders it might be tricky for all: round, ceil and floor
Aug 25, 2017 at 11:32 comment added mjs Oh, yes, my bad, i had mistaken the 2 for 10^53. it suggest a maximum of 10^16, although my experience with random is that 10^12.
Aug 25, 2017 at 9:40 comment added Ionuț G. Stan @momomo you're falling outside the range of safe numbers by using those values. I think the functions are correct given the limitations of numbers in JS: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
Aug 25, 2017 at 9:32 comment added mjs @IonuțG.Stan Challenge accepted. Here are three test runs. hastebin.com/ikefogiyoz.lisp ... see the zeros at the end? That's because Math.random() in JS (ran in Chrome inspector) cannot guarantee more than 12 decimals ( from tests performed, could not find info online on this )
Aug 25, 2017 at 5:06 comment added Ionuț G. Stan @momomo we're looking forward to your answer. Also, not sure where you've tested these, but they work fine for me.
Aug 24, 2017 at 17:20 comment added mjs Try generate a random number between 10^10 and 10^16 and see how it will fail. I wouldn't call random when the last 5 digits are padded with zeros. It gets worse as you go from 10^12 and up ... 10^12 is not even large. There are better ways to get true randomness and utilize the entire 2^53-1.
Aug 14, 2017 at 8:55 comment added user128511 The int one is faster if you use return Math.random() * (max - min) + min | 0; instead of Math.floor. Math.floor is a function on an object which can be replaced and so has to be checked where as | 0 is an operator and therefore can not be replaced and no checks needed.
S May 9, 2017 at 5:12 history suggested Joshua CC BY-SA 3.0
changed MDC to MDN (Mozilla Developer Center to Mozilla Developer Network)
May 8, 2017 at 23:04 review Suggested edits
S May 9, 2017 at 5:12
Jan 26, 2017 at 20:10 comment added Nil @SangameshDavey using Math.max() and Math.min() ?
Mar 8, 2016 at 16:09 comment added David Ortega This question is old, but understanding this answer took me way too much time O.o, I think expanding math.random on next JavaScript version would be kind of useful
S Feb 1, 2016 at 15:55 history suggested Kaspar Lee CC BY-SA 3.0
Mozilla Developer Center correct to Mozilla Developer Network
Feb 1, 2016 at 15:35 review Suggested edits
S Feb 1, 2016 at 15:55
Jan 27, 2016 at 14:19 comment added Ionuț G. Stan @JackFrost yeah, that's right. You're not dumb, you're just learning :)
Jan 27, 2016 at 14:18 comment added JackFrost @IonuțG.Stan thank you so much, being so dumb, the math I gave will give a value between 0 and 5 but then you add the min so it gives between 5 and 10!
Jan 27, 2016 at 8:06 comment added Ionuț G. Stan @JackFrost "Don't forget to add min back, so that we get a number in the [min, max) interval:"
Jan 26, 2016 at 21:02 comment added JackFrost I don't understand the basic concept of this, in the basic form "random * (max - min)" with a max =10 and min = 5 will give "random * 5", surely this would return a value between 0 and 5 rather than between 5 and 10?
Jan 26, 2016 at 16:31 comment added DifferentPseudonym var randomIntRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min; One liner using ES6 arrow functions.
Nov 12, 2014 at 15:43 comment added Adam Zerner I made a little page that does it for you: adamzerner.github.io/randomInRange
Sep 26, 2014 at 19:32 review Suggested edits
Sep 26, 2014 at 20:17
Jul 15, 2014 at 17:04 comment added Evan Hobbs @IonuțG.Stan ah, I see now - I thought you had copied the example directly from the mozilla developer page where the max is exclusive but it looks like you modified it slightly by adding one to make max inclusive (or they changed it after this question). thanks
Jul 14, 2014 at 10:48 comment added Ionuț G. Stan @EvanHobbs not sure what to say... it appears in my quick tests. Are you sure you're using the right function?
Jul 13, 2014 at 3:18 comment added Evan Hobbs @IonuțG.Stan Well by my figuring the probability is 1.0878630073488064e-207 of not getting a 10 if it's possible. I did it several times so it's even more unlikely
Jul 12, 2014 at 19:17 comment added Ionuț G. Stan @EvanHobbs how do you know the 5001st number would not have been 10?
Jul 12, 2014 at 18:19 comment added Evan Hobbs This is great except for getRandomInt() I'm showing that the max is exclusive not inclusive. If I run getRandomInt(0, 10) five thousand times I never get 10 but do get 0. Am I missing something?
Jul 3, 2014 at 0:00 comment added Scuba Josh If you are getting 0 allot wait a little bit... The random function uses time into its equation to give you a random number. So that could be a factor of inconsistency. I would love to see this test on a cron job through out the day with a sum of each number chosen. My reference is here developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
May 28, 2014 at 11:45 history edited Ionuț G. Stan CC BY-SA 3.0
deleted 1 character in body
May 28, 2014 at 3:57 review Suggested edits
May 28, 2014 at 4:03
S May 18, 2014 at 17:20 history suggested Chin CC BY-SA 3.0
make the function descriptions more clear
May 18, 2014 at 17:19 review Suggested edits
S May 18, 2014 at 17:20
Dec 24, 2013 at 21:15 comment added Glen Why add 1 to (max - min)? Because the interval from min to max includes (max - min + 1) integers. Ex: min=4,max=6 means 3 values (4,5,6), not 2, because you count both endpoints. To get 4,5, or 6 equally often from Math.floor(x), which just cuts off the fractional part, you want x to be chosen randomly from an interval that starts at 4 (min) and extends to, but not incl, 7 (max+1). That x interval has a width of (max+1)-min = max-min+1 (there's your answer!) = 3, and chopping off the fractional part of 4.2 or 5.5 or 6.7 leaves you with one of your 3 desired integers, all equally likely.
Jun 5, 2013 at 13:56 comment added ahren I've created a JSFiddle if anyone wants to test the distribution of this method: jsfiddle.net/F9UTG/1
May 16, 2013 at 1:06 history edited fncomp CC BY-SA 3.0
missing comma before but and non to un
Apr 18, 2013 at 14:21 comment added Leo Is anyone getting an unusual amount of Min? I have run this many times on an integer range of [0-10] and I seem to be getting 0 an awful lot. Is it just coincidence? maybe I should use round.
Dec 22, 2012 at 9:44 history edited Christoph CC BY-SA 3.0
added 202 characters in body
Dec 22, 2012 at 9:18 comment added Christoph @thezachperson31 You could use round, but then both, min and max only had half the chance to roll like the other numbers do. You could also substract one and take ceil. This however leaves the max number with a minimal less chance to roll due to the [0,1) Interval.
Oct 6, 2009 at 20:56 history edited Ionuț G. Stan CC BY-SA 2.5
added 2357 characters in body
Oct 6, 2009 at 20:17 comment added Josh Stodola It's only doing that because it's calling floor, which rounds down.
Oct 6, 2009 at 20:12 comment added zacharyliu Could you explain why you need to add one to the max-min? I don't understand that part.
Oct 6, 2009 at 20:12 vote accept zacharyliu
Oct 6, 2009 at 20:08 history answered Ionuț G. Stan CC BY-SA 2.5
toggle format

AltStyle によって変換されたページ (->オリジナル) /