At the beginning of this quarter, we looked at a special object called Math. As we have seen, this object has useful attributes like PI, and E and functions (methods) like abs, sin, and sqrt. Another useful Math object function is the random() function. This function returns a randomly selected real number between 0.0 and 1.0. This means that the expression Math.random() is replaced by a decimal value. The following code will place a randomly selected value in a text box as shown below.

<FORM> <INPUT TYPE='text' NAME='rnum' VALUE=''><BR><BR> <INPUT TYPE='button' VALUE='New Number' onClick="this.form.rnum.value = Math.random()"> </FORM>


Notice that each time you update using the New Number button, a new value is placed in the box. While it is possible that the same number could be displayed two times in a row, it is highly unlikely.

Many programs require the use of "random" numbers other than decimal values between 0 and 1. Using our mathematics knowledge, we can write expressions that generate random numbers in other useful forms. Let us begin by generating random integers.

Math.random( ) 10 * Math.random( ) Math.floor( 10 * Math.random( ) )




By multiplying the random real values by 10, all values are transformed into numbers between 0 and 10. By using the Math.floor( ) function, The real numbers fall to the floor, which is the integer directly below or equal to the real value. The number 9.7 falls to 9. The number 4.3 falls to 4. The number 5.0 remains 5. The 'random' number generator Math.floor( 10 * Math.random( ) ) produces integers between 0 and 9.