Development JavaScript Mathematics

How to Generate Random Numbers in JavaScript

Does your next JavaScript project need a random number to work? Maybe you are creating a poker game for your site? To do this, you need to pick cards in a random way to make it fair.

There are at least two ways to create random numbers with JavaScript. The standard math.random method uses a simple pseudo random method. When you are dealing with encryption, other methods are required. You need to use the Crypto.getRandomValues method in this case.

The simplest use of math.Random is to get a random number. Without any code around it you get a value between 0 and 1 with 16 decimals.   For example:  0.3502547068815538.

Usually, this is not a result anyone wants. In most cases, an integer is needed, for this to happen you need to use a few other math functions. The first example here is the Math.floor function. In this example the result is multiplied by 101 and then the result is rounded down to the nearest integer.

<script>
document.getElementById("result").innerHTML =
Math.floor(Math.random() * 101);
</script>

The value in result will be the lower of the result of Math.random multiplied by 101. The Math.floor function will take the lower integer of the result. Investigate the other methods in the math object; round, ceil for rounding. Note that the round function does not give a uniform distribution, meaning it will be slightly more likely to be high.

You may need to set the number of decimal points in your answer, to do this, use num.ToFixed.

function randomToDecimal() {
  var num = Math.random() * 10;
  var n = num.toFixed(2);
  document.getElementById("demo").innerHTML = n;
}

The range of numbers always start at 0 and goes up, if this is not your preferred range you can create a function that takes a maximum and minimum value.

function randomRange(min, max){
  var res = Math.abs(Math.floor(Math.random() * (max - min) + min));
  document.getElementById("Result").innerHTML = res;
}

function collectRange(){
  var min = document.getElementById("min").value;
  var max = document.getElementById("max").value;
  randomRange(min, max);
}

Calling these functions you can get an arbitrary range from an input field or from another function. The function is extremely simple and ignores which value is max and which is min.

The card example requires a few more classes but the principle stays the same. When you want to choose a card, first you need a deck class.  You can pick one up from github at  https://github.com/pakastin/deck-of-cards

Use the class in the example to pick a random card from the deck. The cards have an index, if you have instantiated correctly, so you can draw card with an index number.

var = deck.card[0];

The above will draw the first card in the deck, by choosing random index you can draw any random card.

// Draw a random card from the deck
function drawACard{
  if (deck.length > 0){
    var index = math.Random() * 52;
    var handCard = deck[index];
  }
  return handCard;
}

Obviously, for a complete implementation you would need to consider where the card goes, is it in a hand, on the table or discarded? That is for another time though.

Going with the casino theme, a pair of dice also needs to have a random function that rolls them.
To throw a dice you just choose the number of sides and mutliply by that.

Var = sides;
var dice = Math.floor(Math.random() * sides)

These examples are great for simple games but when you need to work with cryptography, that the values are slightly biased means security problems

Not random enough

 The math random function is not random enough for cryptographic applications. To secure your communications, and data, you need numbers that are much more random. The Crypto library has a solution for this.  The algorithm is pseudo random, similar to the standard Math. random. However, there is an initial seed for the function that makes the result random enough for cryptographic work.

To use this method you need to call window.crypto.getRandomValues(array). As you may have noticed this function returns an array of numbers. If you need only one number, feel free to set the length of the array to 1.

The crypto library has a few functions for you. These will be useful depending on your needs. The main difference is what you can create as a result. The crypto.randomBytes method gives you a buffer of the size according to the first parameter.  To get a value of your choosing use the buffer.toString method.

There is also the Stanford Javascript Crypto Library, SJCL, which is built especially to encrypt and decrypt data. This library is really small and easy to use but still has a more complex set of functions should you need them.

The most basic use is to just pass the password and the data to the function, like this

Sjcl.encrypt(“password”, “data”)

You can read about the more advanced functions in their documentation or see a demonstration on http://bitwiseshiftleft.github.io/sjcl/demo/

Conclusion

When you are looking to create random numbers, the first thing you need to consider is what you are going to use the random numbers for. A simple game can use the regular Math.random function while encryption requires more advanced methods. Luckily, there are many choices to make your software work exactly the way you want. None of these functions will result in the correct format, that part is your responsibility and a fascinating challenge all of its own.

About the author

Mats Tage Axelsson

Mats Tage Axelsson

I am a freelance writer for Linux magazines. I enjoy finding out what is possible under Linux and how we can all chip in to improve it. I also cover renewable energy and the new way the grid operates. You can find more of my writing on my blog.