Main Page

Previous Next

Mathematical Functions and Constants

Sooner or later you are likely to need mathematical functions in your programs, even if it's only obtaining an absolute value or calculating a square root. Java provides a range of methods that support such functions as part of the standard library stored in the package java.lang, and all these are available in your program automatically.

The methods that support various additional mathematical functions are implemented in the class Math as static methods, so to reference a particular function you can just write Math and a period in front of the name of the method you wish to use. For example, to use sqrt(), which calculates the square root of whatever you place between the parentheses, you would write Math.sqrt(aNumber) to produce the square root of the floating point value in the variable aNumber.

The class Math includes a range of methods for standard trigonometric functions. These are:

Method

Function

Argument Type

Result Type

sin(arg)

sine of the argument

double in radians

double

cos(arg)

cosine of the argument

double in radians

double

tan(arg)

tangent of the argument

double in radians

double

asin(arg)

sin-1 (arc sine) of the argument

double

double in radians with values from –(/2 to (/2.

acos(arg)

cos-1 (arc cosine) of the argument

double

double in radians, with values from 0.0 to (.

atan(arg)

tan-1 (arc tangent) of the argument

double

double in radians with values from –(/2 to (/2.

atan2 (arg1,arg2)

tan-1 (arc tangent) of arg1/arg2

Both double

double in radians with values from –( to (.

As with all methods, the arguments that you put between the parentheses following the method name can be any expression that produces a value of the required type. If you are not familiar with these trigonometric operations you can safely ignore them.

You also have a range of useful numerical functions that are implemented in the class Math. These are:

Method

Function

Argument type

Result type

abs(arg)

Calculates the absolute value of the argument

int, long, float, or double

The same type as the argument

max (arg1,arg2)

Returns the larger of the two arguments, both of the same type

int, long, float, or double

The same type as the argument

min (arg1,arg2)

Returns the smaller of the two arguments, both of the same type

int, long, float, or double

The same type as the argument

ceil(arg)

Returns the smallest integer that is greater than or equal to the argument

double

double

floor(arg)

Returns the largest integer that is less than or equal to the argument

double

double

round(arg)

Calculates the nearest integer to the argument value

float or double

Of type int for a float argument, of type long for a double argument

rint(arg)

Calculates the nearest integer to the argument value

double

double

IEEEremainder (arg1,arg2)

Calculates the remainder when arg1 is divided by arg2

Both of type double

Of type double

The IEEEremainder()method produces the remainder from arg1 after dividing arg2 into arg1 the integral number of times that is closest to the exact value of arg1/arg2. This is somewhat different from the remainder operator. The operation arg1 % arg2 produces the remainder after dividing arg2 into arg1 the integral number of times that does not exceed the absolute value of arg1. In some situations this can result in markedly different results. For example, executing the expression 9.0 % 5.0 results in 4.0, whereas the expression Math.IEEEremainder(9.0,5.0) results in –1.0. You can pick one approach to calculating the remainder or the other, to suit your requirements.

Where more than one type of argument is noted in the table, there are actually several methods, one for each type of argument, but all have the same name. We will see how this is possible in Java when we look at implementing class methods in Chapter 5.

The mathematical functions available in the class Math are:

Method

Function

Argument Type

Result Type

sqrt(arg)

Calculates the square root of the argument

double

double

pow (arg1,arg2)

Calculates the first argument raised to the power of the second argument arg1arg2

Both double

double

exp(arg)

Calculates e raised to the power of the argument earg

double

double

log(arg)

Calculates the natural logarithm (base e) of the argument

double

double

random()

Returns a pseudo-random number greater than or equal to 0.0 and less than 1.0

None

double

The toRadians()method in the class Math will convert a double argument that is an angular measurement in degrees to radians. There is a complementary method, toDegrees(), to convert in the opposite direction. The Math class also defines double values for e and (, which you can access as Math.E and Math.PI respectively.

Let's try out a sample of the contents of the class Math in an example to make sure we know how they are used.

Try It Out – The Math Class

The following program will calculate the radius of a circle in feet and inches, given that it has an area of 100 square feet:

public class MathCalc {
  public static void main(String[] args) {
    // Calculate the radius of a circle
    // which has an area of 100 square feet
    double radius = 0.0;
    double circleArea = 100.0;
    int feet = 0;
    int inches = 0;
    radius = Math.sqrt(circleArea/Math.PI);
    feet = (int)Math.floor(radius); // Get the whole feet and nothing but the feet
    inches = (int)Math.round(12.0*(radius – feet));
    System.out.println("The radius of a circle with area " + circleArea +
                       " square feet is\n " + 
                       feet + " feet " + inches + " inches");
  }
}

Save the program as MathCalc.java. When you compile and run it, you should get:

The radius of a circle with area 100.0 square feet is
 5 feet 8 inches

How It Works

The first calculation, after defining the variables we need, uses the sqrt() method to calculate the radius. Since the area of a circle with radius r is given by the formula (r2, the radius must be ((area/((, and we specify the argument to the sqrt() method as the expression circleArea/Math.PI, where Math.PI references the value of (. The result is in feet as a double value. To get the number of whole feet we use the floor() method. Note that the cast to int is essential in this statement otherwise you will get an error message from the compiler. The value returned from the floor() method is type double, and the compiler will not cast this to int for you automatically because the process potentially loses information.

Finally, we get the number of inches by subtracting the value for whole feet from the original radius, multiplying the fraction of a foot by 12 to get the equivalent inches, and then rounding the result to the nearest integer using the round() method.

Note how we output the result. We specify the combination (or concatenation) of strings and variables as an argument to the println() method. The statement is spread over two lines for convenience here. The \n in the output specifies a newline character, so the output will be on two lines. Any time you want the next bit of output to begin a new line, just add \n to the output string. You can't enter a newline character just by typing it because when you do that the cursor just moves to the next line. That's why it's specified as \n. There are other characters like this that we'll look into now.

Previous Next
JavaScript Editor Java Tutorials Free JavaScript Editor