7 minutes read

Kotlin provides a set of functions to perform calculations. This can be helpful in a variety of fields, for example, statistics, geometry, machine learning, cryptography, and so on.

We will use the library kotlin.math developed specifically for Kotlin; since Kotlin 1.2, it provides common math for the Java platform and JS. You can access all the functions with one line:

import kotlin.math.*

In this topic, we will go through some of the most common functions.

Be careful! Most of these functions work only with Floating-point types, so you need to convert Int or Long types to use them!

Basic functions

You will often need to do simple operations in your work: for example, determining the greater or smaller of two numbers. Luckily, you don't need to do it manually since you can use the Math library.

The following functions work with Int, Long, Float, and Double types (both a and b must be the same type):

  • abs(n) returns the absolute value of its argument;
  • min(a, b) returns the smaller value of two arguments;
  • max(a, b) returns the greater value of two arguments.

Here are some examples:

val abs = abs(-10)     // 10
val dAbs = abs(-10.33) // 10.33

val min = min(11, 81) // 11
val max = max(20, 30) // 30

Power and exponential functions

Another very common operation is taking a square root of some number or raising it to the n-th power. Math library provides separate functions for that:

  • sqrt(x) returns the square root of its argument (works with Float and Double types);
  • x.pow(n) returns the value of x raised to the power of n, where x can be Float or Double and n can be Int, Long, Float, or Double.

If you need to work with logarithms, you can use the functions listed below. Exponential and logarithmic functions work with Float and Double types:

  • exp(x) returns the exponential function of x;
  • ln(x) returns the natural logarithm of x;
  • log(x, base) returns the logarithm of x to base.

Also, Math library provides the constant E that is the base of the natural logarithm.

Now, let's look at the examples:

val sqrt = sqrt(2.0)      // 1.4142...
val square = 5.0.pow(2.0) // 25.0
val cube = 2.0.pow(3.0)   // 8.0


val e = E        // 2.718
val ln = ln(e)   // 1
val log = log(16.0, 4.0)  // 2
val logSum = ln(exp(2.0) * exp(3.0))  // 5

Trigonometric functions

If you need to calculate trigonometric functions such as finding a sine or cosine, the easiest way to do it is, as you may have guessed, Math library.

The following functions work with Float and Double types and accept angles in radians:

  • sin(x) returns the trigonometric sine of the given angle in radians;
  • cos(x) returns the trigonometric cosine of the given angle in radians;
  • tan(x) returns the trigonometric tangent of the given angle in radians.

Also, the library provides the constant PI that is the ratio of the circumference of a circle to its diameter.

Here are some examples:

val pi = PI // pi is 3.1415...

val sin = sin(pi / 2) // 1.0
val cos = cos(pi) // -1.0
val tan = tan(pi / 4) // 0.99999999... (an inaccurate result)

Another helpful operation is calculating the hypotenuse. Imagine we have a right triangle one of whose angles is 90 degrees. We know the lengths of both sides: a = 3.0 and b = 4.0. Here is how we can calculate the length of the hypotenuse:

val a = 3.toDouble()
val b = 4.toDouble()
val c = hypot(a, b) // c is 5.0, function works with Double or Float

The Math library has many other trigonometric functions: you may find arcus and hyperbolic functions on the kotlin.math page.

Rounding functions

You will often need to round numbers. As you may know, there are several different ways to do this.

Rounding functions work with Float and Double types:

  • floor(x) returns the largest double value that is less than or equal to its argument and is equal to an integer;
  • ceil(x) returns the smallest double value that is greater than or equal to its argument and is equal to an integer;
  • round(x) returns the closest double value that is equal to an integer. Numbers like 3.5 or 4.5 are rounded to the nearest even integer. Also, you can use roundToInt() to round number and convert it to Int in one function!

Let's see how they work:

val floor = floor(3.78) // 3.0
val ceil = ceil(4.15)   // 5.0

val negativeFloor = floor(-3.78)  // -4.0
val negativeCeil = ceil(-4.15)    // -4.0

val roundDown = round(4.15)       // 4.0
val roundUp = (4.75).roundToInt() // 5, Int 

val roundDownToEven = round(2.5)  // 2.0
val roundUpToEven = round(3.5)    // 4.0

Example

Now that you know the basic functions, let's try them on a real task.

As you know, the sides of an equilateral triangle are of the same length, and all angles are 60°. We will try to check it using the law of cosines: c2=a2+b22abcos(γ)c^2 = a^2 + b^2 - 2ab\cos(\gamma) where aa and bb are the sides of the triangle and γ\gamma is the angle between them:

val size1 = 6
val size2 = 6
val angle = 60

val a = size1.toDouble()  // pow works with double
val b = size2.toDouble()
val radianAngle = angle * PI / 180 // cos requires an angle in radians

val c = sqrt(a.pow(2.0) + b.pow(2.0) - 2 * a * b * cos(radianAngle))
print(c) // 5.999999999999999, inaccurate, but the correct result

Conclusion

As you can see, the math library provides a lot of helpful functions. With this library, you can perform calculations with numbers, solve trigonometry tasks, and round numbers. This is a kind of functionality that you'll definitely use in your future projects. We cannot cover all functions in one topic, so if we didn't cover a specific function here or you want to see the whole list, check the official page kotlin.math. Good luck!

173 learners liked this piece of theory. 6 didn't like it. What about you?
Report a typo