ZeePedia

Mathematical Functions in JavaScript

<< INTELLIGENT SYSTEMS: techniques for designing Artificial Intelligent Systems
DATA MANAGEMENT >>
img
Introduction to Computing ­ CS101
VU
LESSON 35
MATHEMATICAL METHODS
(WEB DEVELOPMENT LESSON 12)
During the last Lesson we discussed Event handling:
We looked at the concept of event-driven programs and event handlers
What are they?
What do they do?
How do we benefit from them?
We wrote simple programs to demonstrate the capabilities of a few event handlers
What is Event Handling?
Capturing events and responding to them
The system sends events to the program and the program responds to them as they arrive
Events can include things a user does - like clicking the mouse - or things that the system itself does -
like updating the clock. Today we will exclusively focus on user-events.
Event Driven Programs:
Programs that can capture and respond to events are called `event-driven programs'
JavaScript was specifically designed for writing such programs
JavaScript's Handling of Events:
Events handlers are placed in the BODY part of a Web page as attributes in HTML tags
Events can be captured and responded to directly with JavaScript one-liners embedded in HTML tags in
the BODY portion
Alternatively, events can be captured in the HTML code, and then directed to a JavaScript function for
an appropriate response
In-Line JavaScript Event Handling:
Event handlers are placed in the BODY portion of a Web page as attributes of HTML tags
The event handler attribute consists of 3 parts:
The identifier of the event handler
The equal sign
A string consisting of JavaScript statements enclosed in double or single quotes
Multiple JavaScript statements (separated by semicolons) can be placed in that string, but all have to fit
in a single line; no newline characters are allowed in that string
Due to this limitation, sophisticated event handling is not possible with in-line event handling
Usage Guideline:
For very short scripts, "all code in the tag" works well
The "code in the HEAD portion" is the right choice for developing larger JavaScript scripts
It makes the code easier to read
It allows the reuse of a function for multiple event handlers
onFocus & onBlur:
onFocus executes the specified JavaScript code when a window receives focus or when a form element
receives input focus
onBlur executes the specified JavaScript code when a window loses focus or a form element loses focus
233
img
Introduction to Computing ­ CS101
VU
onLoad & onUnload:
onLoad executes the specified JavaScript code when a new document is loaded into a window
onUnload executes the specified JavaScript code when a user exits a document.
Mixed-case capitalization of event handlers (e.g. onClick) is a convention (but not a requirement) for
JavaScript event handlers defined in HTML code
At times, you may wish to use event handlers in JavaScript code enclosed in <SCRIPT>, </SCRIPT>
tags
A Note on Syntax:
In those cases you have to strictly follow the JavaScript rule for all event handler identifiers: they must
all be typed in small case, e.g. `onclick' or `onmouseover'
Today's Goal:(Mathematical Methods)
We will look at JavaScript's Math object
We will look at solutions for simple problems using various methods of the Math object
35.1 Problems & Solutions:
JavaScript doesn't support drawing of graphics
However, crude graphics can be put together with the help of various text characters or tables
One cannot write a character at a random location on the screen using JavaScript
Instead, the graph has to be drawn from top to bottom, one row at a time ­ just like when regular text is
written to a document
<HTML>
<HEAD>
<TITLE>Sine Function Plot</TITLE>
<SCRIPT>
function plotSine( ) {
...
}
...
</SCRIPT>
</HEAD>
<BODY onLoad="plotSine( )">
</BODY>
</HTML>
function plotSine( ) {
var ht, wd, rowN ; // rowN is the row number
234
img
Introduction to Computing ­ CS101
VU
ht = 15 ; // height of the half cycle
wd = 90 ; // width of the plot
document.write(
"<H1 align = 'center'>sin(x)</H1>" ) ;
for( rowN = ht; rowN >= -ht; rowN = rowN - 1 ) {
plotRow( rowN, ht, wd ) ;
}
}
function writeRow( row, wd ) {
var rowE ;
document.write(
"<FONT face = 'courier' size = '-2'>" ) ;
for( rowE = 0; rowE <= wd; rowE = rowE + 1 ) {
document.write ( row[ rowE ] ) ;
}
document.write( "<BR></FONT>" ) ;
}
function plotRow( rowN, ht, wd ) {
var theta, rowE ; // rowE is the row element
var row = new Array( wd ) ;
for ( rowE=0; rowE <= wd; rowE = rowE + 1 ) {
theta = 2 * Math.PI * rowE / wd ;
if( rowN == Math.round(ht * Math.sin( theta )))
row[ rowE ] = "*" ;
else
row[ rowE ] = " " ;
}
writeRow ( row, wd ) ;
}
function plotRow( rowN, ht, wd ) {
var theta, rowE ;
var row = new Array( wd ) ;
for ( rowE=0; rowE <= wd; rowE = rowE + 1 ) {
theta = 2 * Math.PI * rowE / wd ;
if( rowN == Math.round(ht * Math.sin( theta )))
row[ rowE ] = "*" ;
else
if( rowE == 0 )
row[ rowE ] = " " ;
row[ rowE ] = "|" ;
}
else
writeRow ( row, wd ) ;
if( rowN == 0 )
}
row[ rowE ] = "-" ;
else
235
img
Introduction to Computing ­ CS101
VU
That is a sine wave.
How about a cosine?
Or a tangent?
Or, even, the natural logarithm?
Today We Have Seen 3 New Elements:
Math.PI
A property that gave us the value of Pi
Math.round( )
A method that rounded a number to its nearest integer
Math.sin( )
A method that gave us the sine of an angle
All 3 belong to JavaScript's Math object
35.2 Mathematical Functions in JavaScript:
In addition to the simple arithmetic operations (e.g. +, *, etc.) JavaScript supports several advanced
mathematical operations as well
Notationaly, these functions are accessed by referring to various methods of the Math object
Moreover, this object also contains several useful mathematical constants as its properties
This object has no use, but of a placeholder
Properties:
Math.PI
Math.E
Note the CAPITAL
Math.LN2
lettering of all
Math.LN10
properties
Math.LOG2E
Math.LOG10E
Math.SQRT2
Math.SQRT1_2
Methods:
236
img
Introduction to Computing ­ CS101
VU
sin( r )
sqrt( x )
round( x )
pow( x, y )
cos( r )
floor( x )
ceil( x )
tan( r )
asin( x )
exp( x )
acos( x )
abs( x )
log( x )
atan( x )
atan2( x, y )
max( x, y )
max( x, y )
random( )
sin( r ), cos( r ), tan( r ):
Standard trigonometric functions
Returns the sine, cosine or tangent of `r',
where `r' is specified in radians
EXAMPLE
0.707106781186547
document.write( Math.cos( Math.PI / 4 ) )
asin( x ), acos( x ), atan( x ):
Standard inverse-trigonometric functions
Returns the arcsine, arccosine or arctangent of `r'
in radians
EXAMPLE
1.5707963267948965
document.write( Math.asin( 1 ) )
237
img
Introduction to Computing ­ CS101
VU
sqrt( x )
pow( x, y )
Returns the square root of x
Returns x raised to the power y
0.5 0.7071
2, 32
4294967296
exp( x )
log( x )
Returns Math.E raised to
Returns the the natural
the power x
logarithm of x
1 2.718281
Math.E 1
floor( x )
ceil( x )
round( x )
Returns integer nearest
Returns smallest integer
Returns largest integer
to x
that is greater than or
that is less than or
equal to x
equal to x
1.1 1
1.1 1
1.1 2
12.5 13
12.5 12
12.5 13
-13.9 -14
-13.9 -14
-13.9 -13
abs( x )
Returns the absolute
value of x
1.1 1.1
-12.5 12.5
00
min( x, y )
max( x, y )
Returns the smaller of x and y
Returns the larger of x and y
2, 4 4
2, 4 2
-12, -5 -5
-12, -5 -12
238
img
Introduction to Computing ­ CS101
VU
random( ):
Returns a randomly-selected, floating-point number between 0 and 1
EXAMPLE
document.write( Math.random( ) )
0.9601111965589273
random( ):
Example
Design a Web page that displays the result of the rolling of a 6-sided die on user command
****
<HTML>
<HEAD>
<TITLE>Electronic Die</TITLE>
<SCRIPT>
function rollDie( ) { ... }
</SCRIPT>
</HEAD>
<BODY>
<FORM ... > ... </FORM>
</BODY>
</HTML>
<FORM name="form1" method="post" action="">
<INPUT type="submit" name="Submit"
value="Roll Die" onMouseOver="rollDie( )">
<INPUT type="text" name="die" size="12">
</FORM>
Asterisk
function rollDie( ) {
var dieN, dieDots, dots ;
dieDots = "* " ;
dieN = Math.round( 6 * Math.random( ) ) ;
for( dots = 2; dots <= dieN; dots = dots + 1 ) {
dieDots = dieDots + "* " ;
}
document.form1.die.value = dieDots ;
}
During Today's Lesson ...:
We looked at the properties and methods of JavaScript's Math object
We produced solutions for simple problems using several methods of the Math object
239
img
Introduction to Computing ­ CS101
VU
Next (the 13th) Web Dev Lecture:
String Manipulation
To become familiar with a few methods used for manipulating strings
To become able to solve simple problems involving strings
240
Table of Contents:
  1. INTRODUCTION
  2. EVOLUTION OF COMPUTING
  3. World Wide Web, Web’s structure, genesis, its evolution
  4. Types of Computers, Components, Parts of Computers
  5. List of Parts of Computers
  6. Develop your Personal Web Page: HTML
  7. Microprocessor, Bus interface unit, Data & instruction cache memory, ALU
  8. Number systems, binary numbers, NOT, AND, OR and XOR logic operations
  9. structure of HTML tags, types of lists in web development
  10. COMPUTER SOFTWARE: Operating Systems, Device Drivers, Trialware
  11. Operating System: functions, components, types of operating systems
  12. Forms on Web pages, Components of Forms, building interactive Forms
  13. APPLICATION SOFTWARE: Scientific, engineering, graphics, Business, Productivity, Entertainment, Educational Software
  14. WORD PROCESSING: Common functions of word processors, desktop publishing
  15. Interactivity to Forms, JavaScript, server-side scripts
  16. ALGORITHMS
  17. ALGORITHMS: Pseudo code, Flowcharts
  18. JavaScript and client-side scripting, objects in JavaScript
  19. Low, High-Level, interpreted, compiled, structured & object-oriented programming languages
  20. Software Design and Development Methodologies
  21. DATA TYPES & OPERATORS
  22. SPREADSHEETS
  23. FLOW CONTROL & LOOPS
  24. DESIGN HEURISTICS. Rule of thumb learned through trial & error
  25. WEB DESIGN FOR USABILITY
  26. ARRAYS
  27. COMPUTER NETWORKS: types of networks, networking topologies and protocols
  28. THE INTERNET
  29. Variables: Local and Global Variables
  30. Internet Services: FTP, Telnet, Web, eMail, Instant messaging, VoIP
  31. DEVELOPING PRESENTATIONS: Effective Multimedia Presentations
  32. Event Handlers
  33. GRAPHICS & ANIMATION
  34. INTELLIGENT SYSTEMS: techniques for designing Artificial Intelligent Systems
  35. Mathematical Functions in JavaScript
  36. DATA MANAGEMENT
  37. DATABASE SOFTWARE: Data Security, Data Integrity, Integrity, Accessibility, DBMS
  38. String Manipulations:
  39. CYBER CRIME
  40. Social Implications of Computing
  41. IMAGES & ANIMATION
  42. THE COMPUTING PROFESSION
  43. THE FUTURE OF COMPUTING
  44. PROGRAMMING METHODOLOGY
  45. REVIEW & WRAP-UP of Introduction to Computing