# Lesson 11 - Mathematical functions in Kotlin

**Lesson highlights**

Are you looking for a quick reference on the
`kotlin.math`

library instead of a thorough-full lesson? Here it
is:

**Using math constants**:

```
import kotlin.math.*
fun main(args: Array<String>) {
println("Pi: ${PI}, e: ${E}") // using math constants
}
```

**Min/max** of 2 values:

```
import kotlin.math.*
fun main(args: Array<String>) {
println("Min: ${min(5, 10)}")
println("Max: ${max(5, 10)}")
}
```

All **roundings**:

```
import kotlin.math.*
fun main(args: Array<String>) {
println("Round: ${round(-0.2)}")
println("Ceiling: ${ceil(-0.2)}")
println("Floor: ${floor(-0.2)}")
println("Truncate: ${truncate(-0.2)}")
val d = 2.72
val a: Int = round(d).toInt() // casting the rounded double to the int type
}
```

**Abs/signum**:

```
import kotlin.math.*
fun main(args: Array<String>) {
println("Abs: ${abs(-10)}")
println("Sign: ${sign(-10.0)}")
}
```

**Trigonometric** functions:

```
import kotlin.math.*
fun main(args: Array<String>) {
println("Sin: ${sin(PI)}") // almost 0
println("Cos: ${cos(PI)}")
println("Tan: ${tan(PI)}") // almost 0
println("Acos: ${acos(0.0)}")
println("Asin: ${asin(-1.0)}")
println("Atan: ${atan(0.0)}")
}
```

**Powers, roots, logarithms**:

```
import kotlin.math.*
fun main(args: Array<String>) {
println("Pow: ${2.0.pow(3)}")
println("Sqrt: ${sqrt(144.0)}")
println("Exp: ${exp(2.0)}")
println("Log: ${log(100.0, E)}")
println("Log10: ${log10(100.0)}")
}
```

**Dividing whole numbers** in Java always **results
in** another **whole number**:

```
import kotlin.math.*
fun main(args: Array<String>) {
val a = 5 / 2
val b = 5.0 / 2
val c = 5 / 2.0
val d = 5.0 / 2.0
// val e: Int = 5 / 2.0
// val f: Double = 5 / 2
println(a)
println(b)
println(c)
println(d)
}
```

The **remainder** after division (**modulo**):

```
import kotlin.math.*
fun main(args: Array<String>) {
println(5 % 2) // prints 1
}
```

Would you like to learn more? A complete lesson on this topic follows.

In the previous lesson, Multidimensional arrays in Kotlin, we introduced multidimensional arrays. Learning Kotlin 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 successfully got until here, the next online course will be about object oriented programming. We'll be creating really interesting applications and even one game. We'll end this course with a simple article about mathematical functions that will certainly come handy in our future programs.

The basic math functions in Kotlin are contained in the
`kotlin.math`

package. We've already encountered the
`sqrt()`

function to get the square root.

In the older versions of the language, math functions were
called on the `Math`

class, for example as
`Math.sqrt(24.0)`

. Be sure to use the new notation instead where the
functions are called independently.

## Importing the
`kotlin.math`

library

To use the math functions we have to write this line at the top of our file:

import kotlin.math.*

## Constants

We are provided with the following math constants: `PI`

and
`E`

. `PI`

is, of course, the number pi
(`3.1415`

...) and `E`

is the Euler's number, ie. the base
of natural logarithm (`2.7182`

...).

`print("Pi: ${PI}\ne: ${E}")`

The output:

Pi: 3.141592653589793 e: 2.718281828459045

## Available math functions

Now, let's describe the functions the library offers.

The input types support of the functions mentioned below
varies. Some functions are defined for decimal numbers only and some only for,
e.g. `Double`

and `Int`

, but don't support
`Float`

. We already know that when we write a function name and press
`Ctrl` + `Space`, its overloads show up, i.e. the available
ways to call the given function.

Let's say you want to use, for example, the `pow()`

function, see below. For integers, it'd be necessary to cast these numbers to
e.g. the `Double`

type first. We can do this by typing
`(3 as Double).pow(2)`

; this would convert the value of 3 to a
decimal number first and then square it.

`min()`

, `max()`

Let's start with the simple methods Both functions take two numbers of any data type as parameters (but
both parameters has to be of the same type). The `min()`

function
returns the smallest number, the `max()`

function returns the largest
one.

`round()`

,
`ceil()`

, `floor()`

and `truncate()`

All these functions are related to rounding. `round()`

takes a
decimal number as a parameter and returns the rounded number of the
** Double or Float type** in the way we
learned in school (from

`0.5`

it rounds upwards, otherwise
downwards). `ceil()`

(ceiling) rounds always upwards and
`floor()`

rounds downwards no matter what. All these functions are
expecting the `Double`

or `Float`

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

If you think that `floor()`

and `truncate()`

do the
same thing, think again! They behave differently for negative numbers.
`floor()`

rounds negative numbers down to the next "more negative"
number, `truncate()`

always rounds to zero when the input is
negative.

We round decimal numbers and store them in `Int`

variables like
this:

```
var d = 2.72
var a: Int = round(d).toInt()
```

`abs()`

and `sign()`

`abs()`

takes any number of any type as a parameter and returns
its absolute value. `sign()`

takes a decimal number on the input and
returns `-1.0`

, `0.0`

, or `1.0`

depending on
the sign of the number (whether it's negative, zero, or positive).

`sin()`

, `cos()`

,
`tan()`

The classic trigonometric functions, they all take an angle in radians as
`Double`

or `Float`

as a parameter, remember they don't
work with degrees. To convert degrees to radians we multiply them by
`* (PI / 180)`

. The output is a decimal number again.

`acos()`

, `asin()`

,
`atan()`

Again, the classic inverse trigonometric functions (arcus, sometimes
cyclometric functions), which return the original angle according to the
trigonometric value. The parameter is the value as a decimal number, the output
is the angle in radians (also a decimal number). If we wish to have an angle in
degrees, we have to divide the radians by `/ (180 / PI)`

.

`pow()`

and `sqrt()`

We don't call the `pow()`

method globally, but we call it on the
base which is `Double`

or `Int`

. As a parameter, it takes
the exponent as `Double`

or `Int`

. If we wanted to
calculate, for example, `2^3`

, the code would look like this:

println(2.0.pow(3))

`Sqrt()`

is an abbreviation of SQuare RooT, which returns the
square root of the number given as `Double`

or
`Float`

.

`print(sqrt(24.0))`

`exp()`

, `log()`

,
`log10()`

, `log2()`

`exp()`

returns the Euler's number raised to a given decimal
exponent. `log()`

returns the natural logarithm of a given decimal
number. `log10()`

then returns the decadic logarithm (the base is
`10`

) of a given decimal number and `log2()`

the logarithm
with the base `2`

.

Hopefully, you noticed that the method list lacks any general root function.
We, however, can calculate it using the functions `kotlin.math`

provides us with.

We know that roots work like this: 3rd root of `8 = 8^(1/3)`

. So
we can write:

println(8.0.pow((1.0/3.0)))

## 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:

val a = 5 / 2 val b = 5.0 / 2 val c = 5 / 2.0 val d = 5.0 / 2.0 // val e: Int = 5 / 2.0 // val f: Double = 5 / 2 print("$a\n$b\n$c\n$d")

We divide `5/2`

for several times in the code, it 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 be compiled because of the lines with the `e`

a
`f`

variables, which we commented. The problem is that in these cases
the result is a decimal number which we're trying to store into an integer
(`Int`

) or we're storing an integer into `Double`

. The
program's output is as follows:

2 2.5 2.5 2.5

We see the result of this division is sometimes decimal and sometimes whole. If any of the numbers is decimal, the result is also always decimal. Two integers return always an integer. Keep in mind that if you compute the average and want a decimal result, at least one variable must be cast to a decimal number.

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`

), if you want, for example, to draw a checkerboard and fill in
the fields based on whether they are even or odd, calculate the deviance of your
position from some square grid, and so on.

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

:

println(5 % 2) // Prints 1

Well, that's all I've got for you in this course. The course will continue in the section Basics of Object-Oriented Programming in Kotlin. Next time, we'll introduce the world of objects and understand a lot of things that remained unrevealed until now You should surely try the exercises, they contain some console stuff we haven't shown yet and other interesting projects.

In the following exercise, Solved tasks for Kotlin lessons 10-11, we're gonna practice our knowledge from previous lessons.

Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.

### Download

By downloading the following file, you agree to the license terms
Downloaded 12x (6.87 kB)

Application includes source codes in language Kotlin