By default, the random numbers are generated as floating-point numbers between 0 and 1. We change that interval by multiplying by a scaling factor and adding a shift factor to translate the interval.
To generate random integers, we use the random() function from Math along with the floor() function that takes a double value to an integer. The code below generates integers uniformly within a given range. The range of integers is set by choosing the lowest value and the size for the range. To demonstrate the functions, I use them to generate 10 random integers in the specified range and print them.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> <title>XoaX.net's Javascript</title> </head> <body> <script type="text/javascript" src="RandomNumbers.js"></script> </body> </html>
// By default, random numbers are floating-point values in (0, 1) var dRandom = 0.0; document.write("Range: (" + 0.0 + ", " + 1.0 + ")<br />"); document.write("---------------------<br />"); for (var i = 0; i < 10; ++i) { dRandom = Math.random(); document.write("Random# " + i + " = " + dRandom + "<br />"); } document.write("<br />"); // We can adjust the range by multiplying by a stretch factor and adding a shift // With a shift of -2 and stretch factor of 7, this interval is (-2, 5) var dShift = -2.0; var dStretch = 7.0; document.write("Range: (" + dShift + ", " + (dShift + dStretch) + ")<br />"); document.write("---------------------<br />"); for (var i = 0; i < 10; ++i) { dRandom = (dShift + (Math.random()*dStretch)); document.write("Random# " + i + " = " + dRandom + "<br />"); } document.write("<br />"); // Using the floor function, we can generate a range of random integer values var iLow = 6; var iCount = 5; var iRandom = 0; document.write("Integer Range: [" + iLow + "-" + (iLow + iCount - 1) + "]<br />"); document.write("----------------------------<br />"); for (var i = 0; i < 10; ++i) { iRandom = Math.floor((Math.random() * iCount) + iLow); document.write("Random Integer " + i + " = " + iRandom + "<br />"); }
© 20072024 XoaX.net LLC. All rights reserved.