The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.  # Math Methods

In mathematics, you have probably seen functions like sin and log, and you have learned to evaluate expressions like sin(pi/2) and log(1/x). First, you evaluate the expression in parentheses, which is called the argument of the function. For example, pi/2 is approximately 1.571, and 1/x is 0.1 (assuming that x is 10).

Then you can evaluate the function itself, either by looking it up in a table or by performing various computations. The sin of 1.571 is 1, and the log of 0.1 is -1 (assuming that log indicates the logarithm base 10).

This process can be applied repeatedly to evaluate more complicated expressions like log(1/sin(pi/2)). First we evaluate the argument of the innermost function, then evaluate the function, and so on.

Java provides a set of built-in functions that includes most of the mathematical operations you can think of. These functions are called methods. Most math methods operate on doubles.

The math methods are invoked using a syntax that is similar to the print commands we have already seen:

double root = Math.sqrt (17.0);
double angle = 1.5;
double height = Math.sin (angle);

The first example sets root to the square root of 17. The second example finds the sine of 1.5, which is the value of the variable angle. Java assumes that the values you use with sin and the other trigonometric functions (cos, tan) are in radians. To convert from degrees to radians, you can divide by 360 and multiply by 2 pi. Conveniently, Java provides pi as a built-in value:

double degrees = 90;
double angle = degrees * 2 * Math.PI / 360.0;

Notice that PI is in all capital letters. Java does not recognize Pi, pi, or pie.

Another useful method in the Math class is round, which rounds a floating-point value off to the nearest integer and returns an int.

int x = Math.round (Math.PI * 20.0);

In this case the multiplication happens first, before the method is invoked. The result is 63 (rounded up from 62.8319).

Last Update: 2011-01-24