# Lesson 11 - Mathematical functions in Java - The Math library

Java Basic constructs Mathematical functions in Java - The Math library

Last time we learned about multi-dimensional arrays in Java. Learning Java actually starts from now on, however, this online course of the most basic constructs of the language will be finished today. I'm glad that we've successfully reached this point. The next online course is focused on object-oriented programming. We'll create really interesting applications and even one game. We'll end this course with a simple article about mathematical functions that will certainly come in handy in our future programs.

In Java, basic mathematical functions are included in the **Math
class**. The class provides 2 fundamental constants for us: PI and E. PI
is for sure the number Pi (3.1415...), and E is Euler's number, the base of the
natural logarithm (2.7182...). I'm sure you'll get how to work with it, but just
to be sure let's print these constants to the console:

```
{JAVA_CONSOLE}
System.out.println("Pi: " + Math.PI);
System.out.println("e: " + Math.E);
{/JAVA_CONSOLE}
```

We see that we call everything in the Math class.

Console application Pi: 3.141593 e: 2.718282

Now, let's go over the methods that the Math class provides:

## Math class methods

### Min(), max()

Let's start with the simple methods Both functions take two numbers of any data type as parameters. Min() returns the smallest number, max() returns the greatest one.

### Round(), ceil(), floor()

All three functions are related to rounding. Round() takes a decimal number
as parameter and returns the rounded number **of the double data
type** in the way we learned in school (from 0.5 it rounds upwards,
otherwise downwards). Ceil() upwards and floor() rounds downwards no matter
what.

We'll certainly be using round() very often. I practically used the other functions e.g. in determining the number of pages of a guestbook. When we've 33 comments and we print only 10 comments per page, they'll, therefore, occupy 3.3 pages. The result must be rounded up since there will be actually 4 pages.

### Abs() and signum()

Both methods take a number of any type as a parameter. Abs() returns its absolute value and signum() returns a number based on its sign, -1, 0 or 1 (for a negative number, zero and a positive number).

### Sin(), cos(), tan()

Classic trigonometric functions, all take an angle as a double, which has to be entered in radians (not degrees if your country uses them). To convert degrees to radians we multiply them by (Math.PI / 180). The return value is also a double.

### Acos(), asin(), atan()

Inverse trigonometric (arcus, sometimes cyclometric) functions, which return the original angle according to the trigonometric value. The parameter is a double and the returned angle is in radians (also as double). If we wish to have an angle in degrees, we have to divide the radians by (180 / Math.PI).

### Pow() and sqrt()

Pow() takes two `double`

parameters. The first is the base of the
power and the second is the exponent. If we wanted to calculate eg.
2^{3}, the code would be as following:

```
{JAVA_CONSOLE}
System.out.println(Math.pow(2, 3));
{/JAVA_CONSOLE}
```

Sqrt is an abbreviation of SQuare RooT, which returns the square root of the number given as a double. Both functions return a double as the result.

### Exp(), log(), log10()

Exp() returns the Euler's number raised to a given exponent. Log() returns the natural logarithm of a given number. Log10() returns the decadic logarithm of a number.

Hopefully, you noticed that the method list lacks any general root function. We, however, can calculate it using the functions the Math class provides.

We know that roots work like this: 3rd root of 8 = 8^(1/3). So we can write:

```
{JAVA_CONSOLE}
System.out.println(Math.pow(8, (1.0/3.0)));
{/JAVA_CONSOLE}
```

It's very important to write at least one number with a decimal point when we are dividing, otherwise, Java will assume that we want it to apply whole-number division, and the result would have been 8 ^ 0 = 1 in this case.

## Division

Programming languages often differ in how they perform the division of numbers. You need to be aware of these issues to avoid being, unpleasantly, surprised afterwards. Let's write a simple program:

```
{JAVA_CONSOLE}
int a = 5 / 2;
double b = 5 / 2;
double c = 5.0 / 2;
double d = 5 / 2.0;
double e = 5.0 / 2.0;
// int f = 5 / 2.0;
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
System.out.println(e);
{/JAVA_CONSOLE}
```

We divide 5/2 for several times in the code, which is mathematically 2.5. Nonetheless, the results will not be the same in all cases. Can you guess what we'll get in each case? Go ahead, give it a try

The code wouldn't compile because of the line with the variable f, which we commented. The problem is that in this case is that one of the results is a decimal number, which we're trying to assign to an int variable. The program output will be the following:

Console application 2 2.0 2.5 2.5 2.5

We see the result of this division is sometimes decimal and sometimes whole. It doesn't really matter what the data type of the variable we're assigning the result to is. What really matters is the data type of the numbers we divide by. If one of the numbers is decimal, the outcome will always result in a decimal number. Division of 2 integers always returns an integer. Keep in mind that if you compute the average and want a decimal result, at least one variable must be cast to double.

int sum = 10; int count = 4; double average = (double)sum / count;

For example, the PHP language always returns the decimal result of the division. When you divide in different programming languages make sure you check how division works there first before you use it.

### The remainder after division

In our applications, we often need the remainder after integer division (i.e. modulo). In our example 5/2, the integer result is 2 and modulo is 1 (what left over). Modulo is often used to determine whether a number is even (remainder of division by 2 is 0). Modulo is useful if you want, for example, to draw a checkerboard and fill in the fields based on whether they are even or odd, to calculate the deviance of your position from some square grid, and so on.

In Java and C-like languages in general, modulo is a percent sign, i.e. %:

```
{JAVA_CONSOLE}
System.out.println(5 % 2); // prints 1
{/JAVA_CONSOLE}
```

Well, that's all I've got for you in this course. If you'd like to learn more about the Basic constructs of Java or feel like you need more practice, take another look at the articles and lesson-specific exercises. Our Java course will be continued in Basics of object-oriented programming in Java. In the next lesson, we'll introduce you to an object-oriented world. We'll get acquainted with many things that have been kept secret from us until now

### Download

Downloaded 43x (31.54 kB)

Application includes source codes in language Java

**Comments**

No one has commented yet - be the first!