# Lesson 12 - Mathematical functions in VB.NET - The Math library

Last time we learned about multi-dimensional arrays in Visual Basic .NET. Learning VB.NET 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 .NET, 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:

```
{VBNET_CONSOLE}
Console.WriteLine("Pi: {0}", Math.PI)
Console.WriteLine("e: {0}", Math.E)
Console.ReadKey()
{/VBNET_CONSOLE}
```

We see that we call everything in the Math class.

Console application Pi: 3.14159265358979 e: 2.71828182845905

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(), Ceiling(), Floor() and Truncate()

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). Ceiling() upwards and Floor() rounds downwards no matter
what. Truncate() cuts the decimal part off and leaves whole number part intact
(does not round whatsoever).

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:

Dim d As Double = 2.72 Dim a As Integer = Math.Round(d)

The interesting thing is that Round() doesn't return an Integer value but a Double instead. However, Visual Basic will cast it to an Integer automatically.

### Abs() and Sign()

Both methods take a number of any type as a parameter. Abs() returns its absolute value and Sign() 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:

```
{VBNET_CONSOLE}
Console.WriteLine(Math.Pow(2, 3))
{/VBNET_CONSOLE}
```

VB.NET also has the ^ operator which does exactly the same thing:

```
{VBNET_CONSOLE}
Console.WriteLine(2^3)
{/VBNET_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:

```
{VBNET_CONSOLE}
Console.WriteLine(8^(1/3))
{/VBNET_CONSOLE}
```

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

```
{VBNET_CONSOLE}
Dim a As Integer = 5 / 2
Dim b As Double = 5 \ 2
Dim c As Double = 5.0 / 2
Dim d As Double = 5 / 2.0
Dim e As Double = 5.0 / 2.0
Dim f As Integer = 5 / 2.0
Console.WriteLine(a)
Console.WriteLine(b)
Console.WriteLine(c)
Console.WriteLine(d)
Console.WriteLine(e)
Console.WriteLine(f)
Console.ReadKey()
{/VBNET_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 program output will be the following:

Console application 2 2 2.5 2.5 2.5 2

Results of the division using the / operator are always decimal. However, if we store the decimal result into the Integer variable, which is the first result, the decimal part is truncated (not rounded). If we want to perform only the decimal division, we use the \ operator. See the second result which is Integer, even all the data types are Double. Then results are Doubles, the last one is an Integer again.

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 (mod) 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 VB.NET, modulo is a mod operator:

```
{VBNET_CONSOLE}
Console.WriteLine(5 mod 2) ' prints 1
{/VBNET_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 VB.NET or feel like you need more practice, take another look at the articles and lesson-specific exercises. Our Visual Basic course will be continued in Basics of object-oriented programming in VB.NET. 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 4x (82.36 kB)

Application includes source codes in language VB.NET

**Comments**

No one has commented yet - be the first!