The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Learning the Java Language
Lesson: Object Basics and Simple Data Objects

Beyond Basic Arithmetic

The Java programming language supports basic arithmetic computation with its arithmetic operators: +, -, *, /, and %. In the java.lang package, the Java platform provides a class called Math (in the API reference documentation) that provides methods and variables for doing more advanced mathematical computation, such as computing the sine of an angle, or raising a number to a certain power.

The methods in the Math class are class methods, so you call them directly from the class, like this:

Math.round(34.87);
The first set of methods in the Math class that we are going to look at perform various basic mathematical functions, such as computing a number's absolute value and rounding numbers. The following table lists and describes these methods.

Basic Mathematical Functions Implemented by Methods in the Math Class
Method Description
double abs(double)
float abs(float)
int abs(int)
long abs(long)
Returns the absolute value of the argument.
double ceil(double) Returns the smallest double value that is greater than or equal to the argument and is equal to a mathematical integer.
double floor(double) Returns the largest double value that is less than or equal to the argument and is equal to a mathematical integer.
double rint(double) Returns the double value that is closest in value to the argument and is equal to a mathematical integer.
long round(double)
int round(float)
Returns the closest long or int, as indicated by the methodís return value, to the argument.

The following program, BasicMathDemo (in a .java source file) , illustrates how to use some of these methods:

public class BasicMathDemo {
    public static void main(String[] args) {
        double aNumber = -191.635;

        System.out.println("The absolute value of " + aNumber + " is " + Math.abs(aNumber));
        System.out.println("The ceiling of " + aNumber + " is " + Math.ceil(aNumber));
        System.out.println("The floor of " + aNumber + " is " + Math.floor(aNumber));
        System.out.println("The rint of " + aNumber + " is " + Math.rint(aNumber));
    }
}
Here's the output from this program:
The absolute value of -191.635 is 191.635
The ceiling of -191.635 is -191
The floor of -191.635 is -192
The rint of -191.635 is -192
Two other basic methods in the Math class are min and max. The following table shows the different forms of the min and max methods, which compare two numbers and return the smaller or larger, respectively, of the two.

Comparative Functions Implemented by Methods in the Math Class
Method Description
double min(double, double)
float min(float, float)
int min(int, int)
long min(long, long)
Returns the smaller of the two arguments.
double max(double, double)
float max(float, float)
int max(int, int)
long max(long, long)
Returns the larger of the two arguments.

MinDemo (in a .java source file), shown following, uses min to figure out the smaller of two values:

public class MinDemo {
    public static void main(String[] args) {

        double enrollmentPrice = 45.875;
        double closingPrice = 54.375;

        System.out.println("Your purchase price is: $"
                           + Math.min(enrollmentPrice, closingPrice));
    }
}
The program correctly prints the smaller price:

Your purchase price is: $45.875

The next set of methods provided by the Math class are exponential functions. In addition to these functions, you can get the value of e, the base of the natural logarithms, by using Math.E.

Exponential Functions Implemented by Methods in the Math Class
Method Description
double exp(double) Returns the base of the natural logarithms, e, to the power of the argument.
double log(double) Returns the natural logarithm of the argument.
double pow(double, double) Returns of value of the first argument raised to the power of the second argument.
double sqrt(double) Returns the square root of the argument.

The following program, ExponentialDemo (in a .java source file), displays the value of e, then calls each of the methods listed in the previous table on arbitrarily chosen numbers:

public class ExponentialDemo {
    public static void main(String[] args) {
        double x = 11.635;
        double y = 2.76;

        System.out.println("The value of e is " + 
                            Math.E);
        System.out.println("exp(" + x + ") is " + 
                            Math.exp(x));
        System.out.println("log(" + x + ") is " + 
                            Math.log(x));
        System.out.println("pow(" + x + ", " + y + ") is " + 
                            Math.pow(x, y));
        System.out.println("sqrt(" + x + ") is " + 
                            Math.sqrt(x));
    }
}
Here's the output you'll see when you run ExponentialDemo:
The value of e is 2.71828
exp(11.635) is 112984
log(11.635) is 2.45402
pow(11.635, 2.76) is 874.008
sqrt(11.635) is 3.41101
The Math class provides a collection of trigonometric functions, which are summarized in the following table. The value passed into each of these methods is an angle expressed in radians. You can use the toDegrees and toRadians methods to convert from degrees to radians and back. Also, you can use Math.PI to get the double value that is closer than any other to pi, the ratio of a circumference of a circle to its diameter.

Exponential Functions Implemented by Methods in the Math Class
Method Description
double sin(double) Returns the sine of the specified double value.
double cos(double) Returns the cosine of the specified double value.
double tan(double) Returns the tangent of the specified double value.
double asin(double) Returns the arc sine of the specified double value.
double acos(double) Returns the arc cosine of the specified double value.
double atan(double) Returns the arc tangent of the specified double value.
double atan(double) Returns the arc tangent of the specified double value.
double atan2(double) Converts rectangular coordinates (b, a) to polar (r, theta).
double toDegrees(double)*
double toRadians(double)*
Converts the argument to degrees or radians as indicated by the method name.
* Added to the Math class for Java 2 SDK 1.2.

Here's a program, TrigonometricDemo (in a .java source file) , that uses each of these methods to compute various trigonometric values for a 45-degree angle:

public class TrigonometricDemo {
    public static void main(String[] args) {
        double degrees = 45.0;
        double radians = Math.toRadians(degrees);
        
        System.out.println("The value of pi is " + 
                           Math.PI);
        System.out.println("The sine of " + degrees + 
                           " is " + Math.sin(radians));
        System.out.println("The cosine of " + degrees + 
                           " is " + Math.cos(radians));
        System.out.println("The tangent of " + degrees + 
                           " is " + Math.tan(radians));
        System.out.println("The arc sine of " + 
                           Math.sin(radians) + " is " +
                      Math.toDegrees(Math.asin(Math.sin(radians))) +
                           " degrees");
        System.out.println("The arc cosine of " + Math.cos(radians) + 
                           " is " + 
                           Math.toDegrees(Math.acos(Math.cos(radians))) + 
                           " degrees");
        System.out.println("The arc tangent of " + 
                           Math.tan(radians) + " is " + 
                           Math.toDegrees(Math.atan(Math.tan(radians))) + 
                           " degrees");
    }
}


The output of this program is as follows:
The value of pi is 3.141592653589793
The sine of 45.0 is 0.8060754911159176
The cosine of 45.0 is -0.5918127259718502
The tangent of 45.0 is -1.3620448762608377
The arc sine of 45.0 is NaN
The arc cosine of 45.0 is NaN
The arc tangent of 45.0 is 1.570408475869457
Notice that NaN is displayed when the result is undefined for the argument passed into the method. NaN is the acronym for Not a Number. Various methods in the Math class return this value when the result of a particular function is undefined for the argument passed into the method. Both the Double and Float classes contain constants called NaN. By comparing the return value of a method to one of these constants, your program can determine whether the NaN value is returned from a method. Thus, your program can do something reasonable when the mathematical result of a method call is undefined.

The last Math method that we'll cover is random. The random method returns a pseudo-randomly selected number between 0.0 and 1.0. The range includes 0.0 but not 1.0. In other words: 0.0 <= Math.random() < 1.0. To get a number in a different range, you can perform arithmetic on the value returned by the random method. For example, to generate an integer between 1 and 10, you would write:

int number = (int)(Math.random() * 10 + 1);
By multiplying the value by 10, the range of possible values becomes 0.0 <= number < 10.0. By then adding 1, the range of possible values becomes 1.0 <= number < 11.0. Finally, by converting the number to an integer with an explicit cast (int), the value is as desired: an integer value between 1 and 10.

Using Math.random is fine if you need to generate a single number. If you need to generate a series of random numbers, you should create an instance of java.util.Random and call methods on that object to generate numbers. The RandomBag class in the online Bingo example uses this technique to generate a random series of bingo balls. The Math.random method uses an instance of java.util.Random to generate its numbers.


Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.