Sams Teach Yourself JavaScript in 24 Hours Free Open Book

Sams Teach Yourself JavaScript in 24 Hours

Previous Page
Next Page

Working with Math Functions

The Math.random() method generates a random number between 0 and 1. However, it's very difficult for a computer to generate a truly random number. (It's also hard for a human being to do sothat's why dice were invented.)

Today's computers do reasonably well at generating random numbers, but just how good is JavaScript's Math.random function? One way to test it is to generate many random numbers and calculate the average of all of them.

In theory, the average should be somewhere near .5, halfway between 0 and 1. The more random values you generate, the closer the average should get to this middle ground.

As an example of the use of the Math object's methods, you can create a script that tests JavaScript's random number function. To do this, you'll generate 5,000 random numbers and calculate their average.

Did you Know?

Rather than typing it in, you can download and try this hour's example at this book's website.


In case you skipped Hour 7, "Controlling Flow with Conditions and Loops," and are getting out your calculator, don't worryyou'll use a loop to generate the random numbers. You'll be surprised how fast JavaScript can do this.

To begin your script, you will initialize a variable called total. This variable will store a running total of all of the random values, so it's important that it starts at 0:

total = 0;

Next, begin a loop that will execute 5,000 times. Use a for loop because you want it to execute a fixed number of times:

for (i=1; i<=5000; i++) {

Within the loop, you will need to create a random number and add its value to total. Here are the statements that do this and continue with the next iteration of the loop:

   num = Math.random();
   total += num;
}

Depending on the speed of your computer, it might take a few seconds to generate those 5,000 random numbers. Just to be sure something is happening, the script will display a status message after each 1,000 numbers:

if (i % 1000 == 0)
   document.write("Generated " + i + " numbers...<br>");

By the Way

The % symbol in the previous code is the modulo operator, which gives you the remainder after dividing one number by another. Here it is used to find even multiples of 1,000.


The final part of your script will calculate the average by dividing total by 5,000. Your script can also round the average to three decimal places, using the trick you learned earlier in this hour:

average = total / 5000;
average = Math.round(average * 1000) / 1000;
document.write("<H2>Average of 5000 numbers: " + average + "</H2>");

To test this script and see just how random those numbers are, combine the complete script with an HTML document and <script> tags. Listing 8.1 shows the complete random number testing script.

Listing 8.1. A Script to Test JavaScript's Random Number Function

<html>
<head>
<title>Math Example</title>
</head>
<body>
<h1>Math Example</h1>
<p>How random are JavaScript's random numbers?
Let's generate 5000 of them and find out.</p>
<script language="JavaScript" type="text/javascript">
total = 0;
for (i=1; i<=5000; i++) {
    num = Math.random();
    total += num;
    if (i % 1000 == 0)
       document.write("Generated " + i + " numbers...<br>");
}
average = total / 5000;
average = Math.round(average * 1000) / 1000;
document.write("<H2>Average of 5000 numbers: " + average + "</H2>");
</script>
</body>
</html>

To test the script, load the HTML document into a browser. After a short delay, you should see a result. If it's close to .5, the numbers are reasonably random. My result was .502, as shown in Figure 8.1.

Figure 8.1. The random number testing script in action.


By the Way

The average you've used here is called an arithmetic mean. This type of average isn't a perfect way to test randomness. Actually, all it tests is the distribution of the numbers above and below .5. For example, if the numbers turned out to be 2,500 .4s and 2,500 .6s, the average would be a perfect .5but they wouldn't be very random numbers. (Thankfully, JavaScript's random numbers don't have this problem.)


Previous Page
Next Page
Index: [SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T][U][V][W][X][Y]


     Main Menu
Sams Teach Yourself JavaScript in 24 Hours
Table of Contents
Copyright
About the Author
Acknowledgments
Part I: Introducing the Concept of Web scripting and the JavaScript Language
Part II: Learning JavaScript Basics
Hour 5. Using Variables, Strings, and Arrays
Hour 6. Using Functions and Objects
Hour 7. Controlling Flow with Conditions and Loops
Hour 8. Using Built-in Functions and Libraries
Using the Math Object
Working with Math Functions
Using the with Keyword
Working with Dates
Using Third-Party Libraries
Other Libraries
Summary
Q&A
Quiz Questions
Quiz Answers
Exercises
Part III: Learning More About the DOM
Part IV: Working with Advanced JavaScript Features
Part V: Building Multimedia Applications with JavaScript
Part VI: Creating Complex Scripts
Part VII: Appendixes
Index


More Books
PHP Hacks
Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
The Koran (Holy Qur'an)
Macromedia Flash 8 Bible
Search Engine Optimization for Dummies
YouTube Traffic
PHP 5 for Dummies
Harry Potter and The Chamber of Secrets
Harry Potter and the Sorcerer's Stone
The Pilgrim's Progress
Wireless Hacks
Flash Hacks. 100 Industrial-Strength Tips & Tools
PayPal Hacks. 100 Industrial-Strength Tips and Tools
Amazon Hacks
Pdf Hacks
The Da Vinci Code
Google Hacks
The Holy Bible
Windows XP For Dummies
Harry Potter and the Half-Blood Prince
Seo Book
Upgrading and Repairing Networks
Macromedia Dreamweaver 8 UNLEASHED
Windows XP Annoyances
Windows XP Hacks
Microsoft Windows XP Power Toolkit
Teach Yourself MS Office In 24Hours
iPod & iTunes Missing Manual
PC Hacks 100 Industrial-Strength Tips and Tools
PC Overclocking, Optimization, and Tuning - 2th Edition
PC Hardware In A Nutshell 3rd Edition
PC Hardware in a Nutshell, 2nd Edition
Upgrading and Repairing PCs
Google for Dummies
MySQL Cookbook
Teach Yourself Macromedia Flash 8 In 24 Hours
PHP CookBook
Sams Teach Yourself JavaScript in 24 Hours
PHP5 Manual
Free Games Paper Airplanes
500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele