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.
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. |