Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
The Java programming language supports basic arithmetic computation with its arithmetic operators: +, -, *, /, and %. In thejava.lang
package, the Java platform provides a class calledMath
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:The first set of methods in theMath.round(34.87);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
ClassMethod 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,
, illustrates how to use some of these methods:
BasicMathDemo
Here's the output from this program: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)); } }Two other basic methods in theThe 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 -192Math
class aremin
andmax
. The following table shows the different forms of themin
andmax
methods, which compare two numbers and return the smaller or larger, respectively, of the two.
Comparative Functions Implemented by Methods in the Math
ClassMethod 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.
, shown following, uses
MinDemo
min
to figure out the smaller of two values:The program correctly prints the smaller price: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)); } }
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 usingMath.E
.
Exponential Functions Implemented by Methods in the Math
ClassMethod 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,
, displays the value of
ExponentialDemo
e
, then calls each of the methods listed in the previous table on arbitrarily chosen numbers:Here's the output you'll see when you runpublic 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)); } }ExponentialDemo
:TheThe 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.41101Math
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 thetoDegrees
andtoRadians
methods to convert from degrees to radians and back. Also, you can useMath.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.
* Added to the Math class for Java 2 SDK 1.2.
Exponential Functions Implemented by Methods in the Math
ClassMethod 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. Here's a program,
, that uses each of these methods to compute various trigonometric values for a 45-degree angle:
TrigonometricDemo
The output of this program is as follows: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"); } }Notice thatThe 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.570408475869457NaN
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 theMath
class return this value when the result of a particular function is undefined for the argument passed into the method. Both theDouble
andFloat
classes contain constants calledNaN
. By comparing the return value of a method to one of these constants, your program can determine whether theNaN
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 israndom
. Therandom
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:By multiplying the value by 10, the range of possible values becomesint number = (int)(Math.random() * 10 + 1);0.0 <= number < 10.0
. By then adding 1, the range of possible values becomes1.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 ofjava.util.Random
and call methods on that object to generate numbers. TheRandomBag
class in the online Bingo example uses this technique to generate a random series of bingo balls. TheMath.random
method uses an instance ofjava.util.Random
to generate its numbers.
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.