## JavaScript: Random Numbers |

## Math Object |

The Math object is used when complex mathematical functions are needed. To store the value of pi (3.14159...) in the variable 'piValue,' for example, you could write:

var piValue = Math.PI

To take the square root of a variable 'X' and store it in 'Xroot,' you could write:

var xRoot = Math.sqrt(X)

Random Numbers

To generate a random number between 0 and 1 (including 0 and 1) and store it in 'number,' try:

number = Math.random()

To generate a number between 1 and 10, you would need to multiply Math.random() by 9, and then add 1. Multiplying by 9 generates a number between 0 and 9, and adding 1 yields a number between 1 and 10:

number2 = (Math.random() * 9) + 1

The result 'number2' has a decimal, while you probably want an integer. To get an integer, apply the Math.round() function to 'number2':

number3 = Math.round(number2)

Or combine both steps:

number3 = Math.round(Math.random() * 9 + 1)

Let's do an example in which we generate 4 random numbers, similar to what we did above. The ultimate goal is a random number between 1 and 100. Here is the code:

<BODY>

<script language=JavaScript>

<!--

document.write("<em style=font-size:18pt>The following numbers result from 4 separate calls to Math.random(): </em><br><p> " )

number = Math.random()

document.write("The result of Math.random(): ")

document.write("<strong style=font-size:16pt>" + number + "<br><p> </strong>")

number2 = Math.random() * 99

document.write("The result of Math.random() * 99: ")

document.write("<strong style=font-size:16pt>" + number2 + "<br><p> </strong>")

number3 = Math.round(Math.random() * 99)

document.write("The result of Math.round(Math.random() * 99): ")

document.write("<strong style=font-size:16pt>" + number3 + "<br><p> </strong>")

number4 = Math.round(Math.random() * 99) + 1

document.write("The result of Math.round(Math.random() * 99) + 1: ")

document.write("<strong style=font-size:16pt>" + number4 + "<br><p> </strong>")

document.write("<p><em style=font-size:18pt>Hit Refresh or Reload to generate fresh numbers.")

//-->

</script>