Get up to 80 % extra points for free! More info:

Lesson 11 - Mathematical functions in Swift

In the previous lesson, Multidimensional arrays in Swift, we introduced multidimensional arrays.

Learning Swift 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 in handy in our future programs.

In Swift, the basic math functions are contained in the Foundation module which you need for bunch of other features as well. We've already encountered the sqrt() function to get the square root.

We are also provided with the following math constants: M_PI and M_E. M_PI is, of course, the number pi (3.1415...) and E is the Euler's number, i.e. the base of natural logarithm (2.7182...). We can access the pi constant on the Double or Float types as well.

print("Pi: \(Double.pi)\ne: \(M_E)")

The output:

Pi: 3.14159265358979
e: 2.71828182845905

Now, let's go over available math functions.

Available math functions

min(), max()

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

round(), ceil(), floor() and trunc()

All these functions are related to rounding. round() takes a decimal number as a parameter and returns the rounded number of the Double 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. trunc() (truncate) doesn't round, it just cuts the part after the decimal point off. All these functions are expecting the Double type; for Float, there are alternatives with the f suffix, for example: roundf().

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 trunc() do the same thing, think again! They behave differently for negative numbers. floor() rounds negative numbers down to the next "more negative" number, trunc() always rounds to zero when the input is negative.

We round decimal numbers and store them in Int variables like this:

let d = 2.72
let a: Int = Int(round(d))

Casting to Int is necessary; even though round() returns a whole number. However, it's still of the Double type, due to the fact that all mathematical functions work with Double.

abs(), sign, and signum()

You'll probably use abs() more, which takes any number of any type as a parameter and returns its absolute (in other words positive) value. Both the sign property and the signum() method return -1, 0, or 1 depending on the sign of the number (whether it's negative, zero, or positive). The difference is data types. sign is a property of decimal numbers, signum() can be called on Int variables.

sin(), cos(), tan()

The classic trigonometric functions, they all take an angle in radians as Double as a parameter, remember they don't work with degrees. To convert degrees to radians we multiply them by * (M_PI / 180). The output is a Double again. The functions have also Float alternatives.

acos(), asin(), atan()

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 Double, the output is the angle in radians (also a Double). If we wish to have an angle in degrees, we have to divide the radians by / (180 / PI). The functions have also Float alternatives.

pow() and sqrt()

pow() takes two parameters of the Double type. The first is the base of the power and the second is the exponent. Again, we have Float alternatives. If we wanted to calculate, for example, 23, the code would look like this:

print(pow(2, 3))

sqrt() is an abbreviation of SQuare RooT, which returns the square root of the number given as Double. Both functions return the result as Double. There's the sqrtf() function for the Float type.

exp(), log(), log10()

exp() returns the Euler's number raised to a given exponent. log() returns the natural logarithm of a given number. log10() then returns the decadic logarithm (the base is 10) of a given number.

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

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

print(pow(8, (1.0/3.0)))

It's very important that we write at least one number with a decimal point when dividing, otherwise Swift will assume an integer division, resulting in 80 = 1.

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:

let a : Int = 5 / 2
let b : Double = 5 / 2
let c : Double = 5.0 / 2
let d : Double = 5 / 2.0
let e : Double = 5.0 / 2.0
// let f : Int = 5 / 2.0

print("\(a)\n\(b)\n\(c)\n\(d)\n\(e)")

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 f variable, which we commented. The problem is that in this case the result is a decimal number which we're trying to store into an integer (Int). The program's output is as follows:

2
2.5
2.5
2.5
2.5

We see the result of this division is in the first case whole and in other cases decimal. It depends in which type we store to. Although in the second case the division is the same as in the first one, the result is Double because it's the type we store to. The last case (with the f variable) won't work because we divide by 2.0 and Swift tries to store Double to the integer variable.

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 Swift and C-like languages in general, modulo is a percent sign, i.e. %:

print(5 % 2) // Prints 1

Well, that's all I've got for you in this course. The course continues with the Basics of Object-Oriented Programming in Swift course. 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 too.

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


 

Download

By downloading the following file, you agree to the license terms

Downloaded 840x (25.78 kB)

 

Previous article
Multidimensional arrays in Swift
All articles in this section
Swift Basic Constructs
Skip article
(not recommended)
Solved tasks for Swift lesson 10-11
Article has been written for you by Filip Němeček
Avatar
User rating:
1 votes
Activities