Adding Scientific Functions to a Web Page Calculator

In this last part of our six-part series, we shall talk about adding scientific functions to our web page calculator, and then conclude. Scientific functions refer to functions like sin(?), cos(?), tan(?), and log(x). The process is not as difficult as you think. The JavaScript interpreter incorporated into many browsers has some built-in scientific functions. It has most of the functions we shall use. However, it does not have some of the functions we shall use. We shall have to code the pair of functions that JavaScript does not have.

Adding Scientific Functions to a Web Page Calculator - Coding Summary (Page 2 of 4 )

All of the scientific buttons have the onclick attribute. All of the buttons call one new function, which is the scienceFn() function. The ‘y^{x}’ button calls our old operator() function. All of the scientific functions we are dealing with, except the one for ‘y^{x}’, use only one value, namely, the number you type.

The ‘y^{x}’ button does not use the scienceFn() function. When you type a number, and then press a scientific button, the scienceFn() function is called. The scienceFn() function has a switch statement, and each of its cases has a scientific function. So, after you have typed a number and clicked a scientific button, the corresponding scientific function uses the number typed as argument, and is executed. The scienceFn() function copies the result to the display.

The function for the ‘y^{x}’ button needs two values for evaluation. Like the "+" operator, which needs two values for evaluation and uses the operator() function, when you click the ‘y^{x}’ button, the operator() function is called. We shall see the details later. This is the skeleton of the scienceFn() function:

//Science function

function scienceFn(ID)

{

switch (ID)

{

case "BSI":

//give the sine of an angle

break;

case "BCO":

//give the

break;

case "BTA":

//give the tangent of an angle

break;

case "BLN":

//give the natural log of a number

break;

case "BLO":

//give log to base 10 of a number

break;

case "BSQ":

//give the square root of a number

break;

case "BX2":

//give the square of a number

break;

case "BEX":

// Returns E^{no.}, where number is the argument, and E is Euler's constant.

break;

case "BRO":

//round a number to the nearest integer.

break;

}

}

The JavaScript Math Object

JavaScript has a top-level object called the Math object. This object has properties and methods. For example, Math.PI returns the value of pi. Math.cos() returns the cosine of . The methods are of the class and not of the instance of the class. So you do not need the instance of the class to call the method. That is why we use the class name "Math" to call the methods. These methods are called static methods. In fact, all of the properties and methods of the Math class (which is a top level object) are static.