0% found this document useful (0 votes)
45 views13 pages

Generating Random Numbers: Prof. David Rossiter

The document discusses how to generate random numbers in JavaScript. It explains that Math.random() generates a random number between 0 and 1, Math.random()*max_value sets the range, and Math.floor() removes the decimal place. Examples are provided to demonstrate generating a random number, setting the range, and removing the decimal place.

Uploaded by

Wesley Mota
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views13 pages

Generating Random Numbers: Prof. David Rossiter

The document discusses how to generate random numbers in JavaScript. It explains that Math.random() generates a random number between 0 and 1, Math.random()*max_value sets the range, and Math.floor() removes the decimal place. Examples are provided to demonstrate generating a random number, setting the range, and removing the decimal place.

Uploaded by

Wesley Mota
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

GENERATING

RANDOM NUMBERS
PROF. DAVID ROSSITER
1/13

AFTER THIS PRESENTATION


You'll be able to generate and
manipulate random numbers

2/13

WE WILL LOOK AT
Math.random()
Math.floor()

3/13

OVERVIEW
Generate a random number
Set up the range
Throw away the decimal place

4/13

GENERATING A RANDOM NUMBER


You can generate a random number like this:
varrandom_number=Math.random()

The resulting range is [0, 1)


1 will not be generated

5/13

Click here to open the example

6/13

<!doctypehtml>
<html>
<body>
<script>
varrandom_number
random_number=Math.random()
alert(random_number)
</script>
</body>
</html>

7/13

SETTING UP THE RANGE


So far the random number is in the range 0 up to 1
Multiply in order to get the range you want, i.e.
random_number=Math.random()*max_value

We now have a number in the range [0, max_value)

8/13

Click here to open the example

9/13

<!doctypehtml>
<html>
<body>
<script>
varrandom_number
random_number=Math.random()*8
alert("Randomnumberintherange0to"+
"7.9999999:\n"+random_number)
</script>
</body>
</html>

10/13

THROW AWAY THE


DECIMAL PLACE
There is still a decimal place
Math.floor() dumps the decimal place
For example, 2.82248 becomes 2

11/13

Click here to open the example

12/13

<!doctypehtml>
<html>
<body>
<script>
varrandom_number
random_number=Math.random()*50
random_number=Math.floor(random_number)
alert("Randomnumberintherange0to49:"+
random_number)
</script>
</body>
</html>

13/13

You might also like