Using the Math Object


Using the Math Object

You don't need to create an object of the Math type before you use it, you can just use the precreated Math object like this, where I'm using the pow method to create various powers of 2:

 dim var1 = Math.pow(2, 10)  dim var2 = Math.pow(2, 11)  dim var3 = Math.pow(2, 12) 

If you're doing a lot of math calculations, you might want to use the with statement (see "The with Statement" in Chapter 3, "The JavaScript Language: Loops, Functions, and Errors") so that you don't have to preface the Math object's methods with the name Math ; here's how that might look:

 with (Math)  {      dim var1 = pow(2, 10)      dim var2 = pow(2, 11)      dim var3 = pow(2, 12)  } 

I'll take a look at some of the ways of using the Math object now.

Performing Calculations

When you need to perform math calculations in JavaScript, you turn to the Math object. As you can see in Table 19.3, plenty of math methods built in to this object, from log to exp , go far beyond the standard JavaScript operators. (See Table 2.3 for the JavaScript operators and what they do.) Here's an example, a simple calculator, which enables the user to calculate all kinds of quantities , from absolute values to cosines at the click of a button:

(Listing 19-01.html on the web site)
 <HTML>      <HEAD>          <TITLE>              The Easy Calculator          </TITLE>          <SCRIPT LANGUAGE="JavaScript">              <!--             function abs()              {                  document.form1.text1.value = Math.abs(document.form1.text1.value)              }              function cos()              {                  document.form1.text1.value = Math.cos(document.form1.text1.value)              }              function exp()              {                  document.form1.text1.value = Math.exp(document.form1.text1.value)              }              function floor()              {                  document.form1.text1.value = Math.floor(document.form1.text1.value)              }              function log()              {                  document.form1.text1.value = Math.log(document.form1.text1.value)              }              function sqrt()              {                  document.form1.text1.value = Math.sqrt(document.form1.text1.value)              }              // -->          </SCRIPT>      </HEAD>      <BODY>          <H1>The Easy Calculator</H1>          <FORM NAME="form1">              <INPUT TYPE="TEXT" NAME="text1">              <BR>              <INPUT TYPE="BUTTON" ONCLICK="abs()" VALUE="&nbsp;Abs&nbsp;">              <INPUT TYPE="BUTTON" ONCLICK="cos()" VALUE="&nbsp;Cos&nbsp;">              <INPUT TYPE="BUTTON" ONCLICK="exp()" VALUE="&nbsp;Exp&nbsp;">              <BR>              <INPUT TYPE="BUTTON" ONCLICK="floor()" VALUE="Floor">              <INPUT TYPE="BUTTON" ONCLICK="log()" VALUE="&nbsp;Log&nbsp;">              <INPUT TYPE="BUTTON" ONCLICK="sqrt()" VALUE="&nbsp;Sqrt">          </FORM>      </BODY>  </HTML> 

You can see the results in Figure 19.1.

Figure 19.1. The easy calculator.

graphics/19fig01.gif

Random Numbers

You can use the random method to create random numbers from 0 to 1, which is great for all kinds of uses, from statistics to games .

Tip

If you need a random number between a and b , you can use the expression a + Math.random() * (b - a) .


Here's an example. In this case, I'll create a fictitious bar graph that displays a stock projection for several years . I'll assemble the bar graph using a single red piece of a bar, piece.jpg, over and overthe number of times the piece displays in each bar will be set by Math.random .

I'll display the bar graph in a <DIV> element, div1 , using the innerHTML property of that element (note that this example is targeted to NS6+ and IE4+ because I'm using the getElementById method here):

 function draw()  {      html = "2003: " + doPieces()      html += "2004: " + doPieces()      html += "2005: " + doPieces()      html += "2006: " + doPieces()      document.getElementById("div1").innerHTML = html  } 

The doPieces function just assembles each bar in the graph, using <IMG> elements, using Math.random to determine how many pieces to assemble in each bar:

 function doPieces()  {      var piece = "<IMG SRC='piece.jpg'>", text = ""      var number = Math.floor(5 * Math.random()) + 1      for (var loopIndex = 0; loopIndex < number; loopIndex++){          text += piece      }      return text + "<BR>"  } 

You can see the results in Figure 19.2. Click the button a few times to see an entirely different stock projection.

Figure 19.2. Generating a random graph.

graphics/19fig02.gif

Here's the full code for this example:

(Listing 19-02.html on the web site)
 <HTML>      <HEAD>          <TITLE>              Random Numbers          </TITLE>          <SCRIPT LANGUAGE="JavaScript">              <!--             function draw()              {                  html = "2003: " + doPieces()                  html += "2004: " + doPieces()                  html += "2005: " + doPieces()                  html += "2006: " + doPieces()                  document.getElementById("div1").innerHTML = html              }              function doPieces()              {                  var piece = "<IMG SRC='piece.jpg'>", text = ""                  var number = Math.floor(5 * Math.random()) + 1                  for (var loopIndex = 0; loopIndex < number; loopIndex++){                      text += piece                  }                  return text + "<BR>"              }              // -->          </SCRIPT>      </HEAD>      <BODY>          <H1>Random Numbers</H1>          SteveCo Stock Projection:          <FORM NAME="form1">              <DIV ID="div1"></DIV>              <BR>              <INPUT TYPE="BUTTON" ONCLICK="draw()" VALUE="Get New Stock Projection">          </FORM>      </BODY>  </HTML> 

Finding Absolute Values and Rounding Down

Two of the biggest uses for the Math object are finding absolute values and rounding values down, for which you use the abs and floor methods. In fact, we've already seen these methods at work in Chapter 18, "The Date , Time , and String Objects" (Listing 18-03.html), where we subtracted two dates to find the number of days between them:

 <HTML>      <HEAD>          <TITLE>              Date Subtractor          </TITLE>          <SCRIPT LANGUAGE="JavaScript">              <!--  function showTime()   {   var date1, date2   date1 = new Date(document.form1.text1.value)   date2 = new Date(document.form1.text2.value)   var difference   difference = Math.abs(date1.getTime() - date2.getTime())   document.form1.text3.value =   Math.floor(difference / (1000 * 60 * 60 * 24)) + " days"   }  // -->          </SCRIPT>      </HEAD>      <BODY>          <H1>Date Subtractor</H1>          <FORM NAME="form1">              <CENTER>              <INPUT TYPE="TEXT" NAME="text1">              <BR>              -             <BR>              <INPUT TYPE="TEXT" NAME="text2">              <BR>              <INPUT TYPE="BUTTON" ONCLICK="showTime()"              VALUE="&nbsp;&nbsp;=&nbsp;&nbsp;">              <BR>              <INPUT TYPE="TEXT" NAME="text3">              </CENTER>          </FORM>      </BODY>  </HTML> 


Inside Javascript
Inside JavaScript
ISBN: 0735712859
EAN: 2147483647
Year: 2005
Pages: 492
Authors: Steve Holzner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net