avatarDr. Derek Austin 🥳

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

2710

Abstract

0 to 1 with 2 digits of precision would be:</p><div id="b9ff"><pre><span class="hljs-attribute">Math</span>.floor(Math.random()*<span class="hljs-number">100</span>)/<span class="hljs-number">100</span> // A number <span class="hljs-number">0</span> <= x < <span class="hljs-number">1</span> e.g. <span class="hljs-number">0</span>.<span class="hljs-number">07</span></pre></div><h1 id="9ffe">Can you set a seed with Math.random()?</h1><p id="d946">Pseudorandom numbers have a <a href="https://en.wikipedia.org/wiki/Random_seed">seed</a>, which if configurable can be used to reproduce the same set of “random” numbers repeatedly.</p><p id="53c3">That would be useful for something like automated testing of an algorithm on a large, random data-set that you don’t want to store as mock-up data.</p><p id="806f">Unfortunately, <code>Math.random()</code> does not allow you to set the seed.</p><p id="c114" type="7">“The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user.” — MDN Docs</p><p id="5b8b">So, if you need reproducible seeds for testing data, you will need a third-party library, like the open-source <a href="https://github.com/davidbau/seedrandom">seedrandom.js</a> (available on GitHub).</p><h1 id="6a40">How random is Math.random()?</h1><p id="dd80">The exact mathematical randomness generated by <code>Math.random()</code> in terms of <a href="https://en.wikipedia.org/wiki/Entropy_(computing)">bits of entropy</a> varies depending on the platform.</p><p id="8d17">That’s because <a href="https://tc39.es/ecma262/#sec-math.random">the ECMAScript specification</a> simply specifies what <code>Math.random()</code> should return, now how it should be implemented.</p><blockquote id="2ced"><p>“Despite <code>Math.random()</code> being capable of producing numbers within [0, 1), there are a few downsides to doing so:</p></blockquote><blockquote id="6946"><p>It is inconsistent between engines as to how many bits of randomness:</p></blockquote><blockquote id="63a7"><p>Internet Explorer: 53 bits</p></blockquote><blockquote id="13ec"><p>Mozilla Firefox: 53 bits</p></blockquote><blockquote id="6264"><p>Google Chrome/node.js: 32 bits [*Now 128 bits, see below]</p></blockquote><blockquote id="6ec1"><p>Apple Safari: 32 bits” — <a href="https://github.com/ckknight/random-js">random-js repository on GitHub</a></p></blockquote><p id="f413">*The V8 engine that powers Chrome and Node was updated to a 128-bit <code>Math.random()</code> implementation in 2015, <a href="https://v8.dev/blog/math-random">according to the V8 blog</a>.</p><p id="8316">So, you may want to search for another library if you need something more

Options

random than that, though 32-bits (i.e. <a href="https://en.wikipedia.org/wiki/4,294,967,295">4294967295</a>) is probably plenty.</p><p id="b7ba">The fact that the degree of entropy varies between platforms inconsistently is more of the downside than the 32-bit limitation.</p><h1 id="a77a">Math.random() is not cryptographically secure</h1><p id="507b">Additionally, <code>Math.random()</code> is not suitable for cryptography, and the MDN Docs recommend you use an alternative like the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Crypto">Web Crypto API</a>.</p><p id="3278" type="7">“Math.random() does not provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the window.crypto.getRandomValues() method.” — MDN Docs</p><p id="b9ac">When working in a secure context (i.e. via HTTPS/TLS), the built-in Web Crypto API can provide cryptographically secure number generation.</p><p id="0a15">Medium author <a href="undefined">Daz</a> gives a simple example of using the Web Crypto API’s <a href="https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues"><code>.getRandomValue</code>s()</a> method <a href="https://readmedium.com/generating-cryptographic-random-state-in-javascript-in-the-browser-c538b3daae50">in an article on his blog</a>.</p><p id="b459">There are also free libraries on GitHub for cryptographically secure numbers, such as <a href="https://github.com/jprichardson/secure-random">secure-random</a> or the 🤓 emoji-friendly 🧐 <a href="https://github.com/macmcmeans/isaacCSPRNG">isaacCSPRNG</a>.</p><p id="2060">But for your day-to-day insecure random numbers, such as when learning <a href="https://readmedium.com/sorts-in-60-seconds-speedy-javascript-interview-answers-on-sorting-acb72bdea8a2">JavaScript sorting algorithms</a> or <a href="https://readmedium.com/how-to-sort-an-array-numerically-in-javascript-2b22710e3958">how to sort an array numerically</a>, <code>Math.random()</code> will work just fine. <b>Happy coding!</b> 🤠🥳😎</p><figure id="5e46"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*p7HGyCw-c4Na7e8U"><figcaption>Photo by <a href="https://unsplash.com/@carsonarias?utm_source=medium&amp;utm_medium=referral">Carson Arias</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p id="0640"><a href="https://www.linkedin.com/in/derek-austin/">Dr. Derek Austin</a> is the author of <a href="https://www.amazon.com/dp/B0BRJDLJ43"><i>Career Programming: How You Can Become a Successful 6-Figure Programmer in 6 Months</i></a>, now available on Amazon.</p></article></body>

Working with the built-in Math.random() method

How to Generate Random Numbers in JavaScript

Whether for performance testing or any other purpose, it is sometimes useful to generate pseudorandom numbers.

Photo by Kristopher Roller on Unsplash

“The Math.random() function returns a floating-point, pseudo-random number in the range 0 to less than 1 (inclusive of 0, but not 1) with approximately uniform distribution over that range — which you can then scale to your desired range.” — MDN Docs

JavaScript has a useful built-in Math.random() function that generates pseudorandom floating-point numbers in a pinch:

Math.random() // A number 0 <= x < 1, e.g. 0.6185746631788063

To generate an integer number in a certain range, inclusive, use this code:

Math.floor(Math.random() * 1 - Low + High)) + Low // Low <= x < High

For example, a random integer from 1 to 10 would be:

Math.floor(Math.random() * (1 - 1 + 10)) + 1 // 1 <= x <= 10

A random floating point from 1 to 10 would be:

Math.random() * (9) + 1 // 1 <= x < 10 e.g. 3.260141980146828

A random floating point from 0 to 1 with 2 digits of precision would be:

Math.floor(Math.random()*100)/100 // A number 0 <= x < 1 e.g. 0.07

Can you set a seed with Math.random()?

Pseudorandom numbers have a seed, which if configurable can be used to reproduce the same set of “random” numbers repeatedly.

That would be useful for something like automated testing of an algorithm on a large, random data-set that you don’t want to store as mock-up data.

Unfortunately, Math.random() does not allow you to set the seed.

“The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user.” — MDN Docs

So, if you need reproducible seeds for testing data, you will need a third-party library, like the open-source seedrandom.js (available on GitHub).

How random is Math.random()?

The exact mathematical randomness generated by Math.random() in terms of bits of entropy varies depending on the platform.

That’s because the ECMAScript specification simply specifies what Math.random() should return, now how it should be implemented.

“Despite Math.random() being capable of producing numbers within [0, 1), there are a few downsides to doing so:

It is inconsistent between engines as to how many bits of randomness:

Internet Explorer: 53 bits

Mozilla Firefox: 53 bits

Google Chrome/node.js: 32 bits [*Now 128 bits, see below]

Apple Safari: 32 bits” — random-js repository on GitHub

*The V8 engine that powers Chrome and Node was updated to a 128-bit Math.random() implementation in 2015, according to the V8 blog.

So, you may want to search for another library if you need something more random than that, though 32-bits (i.e. 4294967295) is probably plenty.

The fact that the degree of entropy varies between platforms inconsistently is more of the downside than the 32-bit limitation.

Math.random() is not cryptographically secure

Additionally, Math.random() is not suitable for cryptography, and the MDN Docs recommend you use an alternative like the Web Crypto API.

“Math.random() does not provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the window.crypto.getRandomValues() method.” — MDN Docs

When working in a secure context (i.e. via HTTPS/TLS), the built-in Web Crypto API can provide cryptographically secure number generation.

Medium author Daz gives a simple example of using the Web Crypto API’s .getRandomValues() method in an article on his blog.

There are also free libraries on GitHub for cryptographically secure numbers, such as secure-random or the 🤓 emoji-friendly 🧐 isaacCSPRNG.

But for your day-to-day insecure random numbers, such as when learning JavaScript sorting algorithms or how to sort an array numerically, Math.random() will work just fine. Happy coding! 🤠🥳😎

Photo by Carson Arias on Unsplash

Dr. Derek Austin is the author of Career Programming: How You Can Become a Successful 6-Figure Programmer in 6 Months, now available on Amazon.

JavaScript
Programming
Mathematics
Software Engineering
Web Development
Recommended from ReadMedium