© Doug Winnie 2021
D. WinnieEssential Java for AP CompScihttps://doi.org/10.1007/978-1-4842-6183-5_19

19. Math Methods

Doug Winnie1  
(1)
Mission Hills, KS, USA
 

Basic math operators will only get you so far. There are a bunch more that you can use to do things with more advanced methods like algebra, trigonometry, statistics, calculus, and more in Java.

Working with Simple Methods

The most basic is working with numbers and rounding them. There are three ways to deal with a decimal value on a number.

The first is to just eliminate it entirely. This is called finding the number’s floor. Any decimal value is simply removed. Even if it is .99999.

The second is to take any decimal value and raise it up to the next whole number, called the number’s ceiling. Any decimal value will move the number to the next whole number. Even if it is .00001.

The last is to do traditional rounding. Anything .5 or higher moves up to the next whole number. Anything below .5 moves down.

To perform these actions, we need to call a method.

A method is a named section of code that we can execute just by calling the name (followed by a pair of parentheses).

Some methods return a value, like our rounding examples mentioned earlier. When a method returns a value, the value that is returned essentially replaces the name of the method when it is called.

In order for most methods to work though, you need to give it something to work with. We provide values to the method by placing them in the pair of parentheses that follows the method name.

Take this example that uses the ceil() method to raise any decimal value to the next whole number:
double a = 1.25;
double b = Math.ceil(a);
System.out.println(b);
// Output: 2.0

The variable a is provided to the Math.ceil() method which then performs the ceiling method. It returns a value of 2.0, which replaces the method call. That value is then assigned to b.

You can put anything that evaluates to a required parameter in a method call, including mathematical operators or other variables. You can even call another method within a method call.

Multiparameter Methods

Some methods like finding the value of a base number raised exponentially need to provide the method with two values. You can provide two values to methods that require it by separating them with a comma:
double x = 2.0;
double y = 8.0;
double z = Math.pow(x,y);
System.out.println(z);
// Output: 256

Illegal Value Types in Methods

Some methods require specific types of values, or they won’t work. IntelliJ will let you know when it encounters a potentially illegal value. If it encounters it when it builds and runs the program, you’ll get an error:
float foo = 5.5f;
float bar = Math.floor(foo);
// Error, floor() requires a double

Math Constants

There are special values that you can refer to by name in Java that represent special irrational numbers that are constant and never change. The most common is π and e.

These are presented by using the phrases Math.E and Math.PI.

Code Examples

The next page shows examples of basic math methods that you can use in your programs.

This code is also available in the following GitHub repo:

https://github.com/Apress/essential-java-AP-CompSci
public class Main {
    public static void main(String[] args) {
        // I: Number methods
        double a = Math.floor(1.99); // a = 1
        double b = Math.ceil(1.01);  // b = 2
        double c = Math.round(1.49); // c = 1
        System.out.printf("Rounding >> floor %f >> ceil %f >> round %f ", a, b, c);
        // Output: Rounding >> floor 1.000000 >> ceil 2.000000 >> round 1.000000
        // II: Algebraic methods
        double d = Math.pow(2,8);    // d = 256.0
        double e = Math.sqrt(256.0); // e = 128.0
        double f = Math.cbrt(27);    // f = 3.0
        double g = Math.PI;          // Represents pi
        double h = Math.E;           // Represents Euclid's number
        double i = Math.log(50);     // Returns the *natural* logarithm
        double j = Math.log10(50);   // Returns the common (base-10) logarithm
        double k = Math.abs(-1);     // k = 1.0
        System.out.printf("%f, %f, %f, %f, %f, %f, %f, %f ",d,e,f,g,h,i,j,k);
        // Output: 256.000000, 16.000000, 3.000000, 3.141593, 2.718282, 3.912023, 1.698970, 1.000000
        // III: Trigonometric methods
        double l = Math.sin(2);      // Returns sine (using radians)
        double m = Math.cos(2);      // Returns cosine (using radians)
        double n = Math.tan(2);      // Returns tangent (using radians)
        double o = Math.asin(1);     // Returns arc sine (using radians)
        double p = Math.acos(1);     // Returns arc cosine (using radians)
        double q = Math.atan(2);     // Returns arc tangent (using radians)
        double r = Math.toRadians(90.0);            // Returns radians
        double s = Math.toDegrees(Math.PI * 2);     // Returns degrees
        double t = Math.cos(Math.toRadians(Math.PI * 2)); // Nested method calls
        System.out.printf("%f, %f, %f, %f, %f, %f, %f, %f, %f ",l,m,n,o,p,q,r,s,t);
        // Output: 0.909297, -0.416147, -2.185040, 1.570796, 0.000000, 1.107149, 1.570796, 360.000000, 0.993993
        // IV: Comparison methods
        double max = Math.max(1,2);  // Returns 2
        double min = Math.min(1,2);  // Returns 1
        System.out.printf("%f, %f",max,min);
        // Output: 2.000000, 1.000000
    }
}
Listing 19-1

Common math methods

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.157.186