java.lang.Math


The class java.lang.Math provides a utility library of mathematical functions. It also provides constant definitions Math.E, for the base of the natural log, and Math.PI, to represent pi. These constants are double quantities that provide fifteen decimal places.

The Java API library also contains a class named java.lang.StrictMath, which provides bit-for-bit adherence to accepted standard results for the functions. For most purposes, Math is acceptable and also results in better performance.

I summarize the functions provided by the Math class in the following table. Refer to the Java API documentation for complete details on each function.

Method Name(s)

Functionality

abs

absolute value; overloaded for all primitive numeric types

max, min

maximum and minimum value

acos, asin, atan

arc cosine, arc sine, arc tangent

cos, sin, tan

cosine, sine, tangent

atan2

convert (x, y) coordinates to polar

ceil, floor, round

ceiling, floor, and rounding capabilities

exp

e raised to a power

log

natural log

pow

x raised to y

sqrt

square root

random

random from 0.0 to 1.0

rint

closest int value for a double

toDegrees, toRadians

convert between degrees and radians

IEEERemainder

IEEE 754 remainder for double operation x / y


A method to calculate the hypotenuse of a right triangle provides a simple example. (The hypotenuse is the side opposite the right angle.)

 // util.MathTest.java: package util; import junit.framework.*; public class MathTest extends TestCase {    static final double TOLERANCE = 0.05;    public void testHypotenuse() {       assertEquals(5.0, Math.hypotenuse(3.0, 4.0), TOLERANCE);    } } // in util.Math: package util; import static java.lang.Math.*; public class Math {    public static double hypotenuse(double a, double b) {       return sqrt(pow(a, 2.0) + pow(b, 2.0));    } } 

The pow function is used to square the sides a and b. The hypotenuse method then sums these squares and returns the square root of the sum using sqrt.

Pervasive use of the Math class gives you a justifiable reason for using the static import facility introduced in Lesson 4. Code with a lot of Math method calls otherwise becomes a nuisance to code and read.

I've named the utility class Math, like the java.lang.Math class. While this is a questionable practice (it may introduce unnecessary confusion), it demonstrates that Java can disambiguate the two.



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net