## How To Do Math in Go with Operators

Numbers are common in programming. They are used to represent things such as: screen-size dimensions, geographic locations, money and points, the amount of time that passes in a video, positions of game avatars, colors through assigning numeric codes, and so on.

Effectively performing mathematical operations in programming is an important skill to develop because of how frequently you’ll work with numbers. Though a high-level understanding of mathematics can certainly help you become a better programmer, it is not a prerequisite. If you don’t have a background in mathematics, try to think of math as a tool to accomplish what you would like to achieve, and as a way to improve your logical thinking.

We’ll be working with two of Go’s most used numeric data types, integers and floats:

• Integers are whole numbers that can be positive, negative, or 0 (…, `-1`, `0`, `1`, …).
• Floats are real numbers that contain a decimal point, like `9.0` or `-2.25`..

This tutorial will review operators that we can use with number data types in Go.

## Operators

An operator is a symbol or function that indicates an operation. For example, in math the plus sign or `+` is the operator that indicates addition.

In Go, we will see some familiar operators that are brought over from math. However, other operators we will use are specific to computer programming.

Here is a quick reference table of math-related operators in Go. We’ll be covering all of the following operations in this tutorial.

Operation What it returns
`x + y` Sum of `x` and `y`
`x - y` Difference of `x` and `y`
`-x` Changed sign of `x`
`+x` Identity of `x`
`x * y` Product of `x` and `y`
`x / y` Quotient of `x` and `y`
`x % y` Remainder of `x` / `y`

We’ll also be covering compound assignment operators, including `+=` and `*=`, that combine an arithmetic operator with the `=` operator.

In Go, addition and subtraction operators perform just as they do in mathematics. In fact, you can use the Go programming language as a calculator.

Let’s look at some examples, starting with integers:

``fmt.Println(1 + 5) ``
``Output6 ``

Instead of passing integers directly into the `fmt.Println` statement, we can initialize variables to stand for integer values by using syntax like the following:

``a := 88 b := 103  fmt.Println(a + b) ``
``Output191 ``

Because integers can be both positive and negative numbers (and 0 too), we can add a negative number with a positive number:

``c := -36 d := 25  fmt.Println(c + d) ``
``Output-11 ``

Addition will behave similarly with floats:

``e := 5.5 f := 2.5  fmt.Println(e + f) ``
``Output8 ``

Because we added two floats together, Go returned a float value with a decimal place. However, since the decimal place is zero in this case, `fmt.Println` dropped the decimal formatting. To properly format the output, we can use `fmt.Printf` and the verb `%.2f`, which will format to two decimal places, like this example:

``fmt.Printf("%.2f", e + f) ``
``Output8.00 ``

The syntax for subtraction is the same as for addition, except we change our operator from the plus sign (`+`) to the minus sign (`-`):

``g := 75.67 h := 32.0  fmt.Println(g - h) ``
``Output43.67 ``

In Go, we can only use operators on the same data types. We can’t add an `int` and a `float64`:

``i := 7 j := 7.0 fmt.Println(i + j) ``
``Outputi + j (mismatched types int and float64) ``

Trying to use operators on data types that are not the same will result in a compiler error.

## Unary Arithmetic Operations

A unary mathematical expression consists of only one component or element. In Go we can use the plus and minus signs as a single element paired with a value to: return the value’s identity (`+`), or change the sign of the value (`-`).

Though not commonly used, the plus sign indicates the identity of the value. We can use the plus sign with positive values:

``i := 3.3 fmt.Println(+i) ``
``Output3.3 ``

When we use the plus sign with a negative value, it will also return the identity of that value, and in this case it would be a negative value:

``j := -19 fmt.Println(+j) ``
``Output-19 ``

With a negative value the plus sign returns the same negative value.

The minus sign, however, changes the sign of a value. So, when we pass a positive value we’ll find that the minus sign before the value will return a negative value:

``k := 3.3 fmt.Println(-k) ``
``Output-3.3 ``

Alternatively, when we use the minus sign unary operator with a negative value, a positive value will be returned:

``j := -19 fmt.Println(-j) ``
``Output19 ``

The unary arithmetic operations indicated by the plus sign and minus sign will return either the value’s identity in the case of `+i`, or the opposite sign of the value as in `-i`.

## Multiplication and Division

Like addition and subtraction, multiplication and division will look very similar to how they do in mathematics. The sign we’ll use in Go for multiplication is `*` and the sign we’ll use for division is `/`.

Here’s an example of doing multiplication in Go with two float values:

``k := 100.2 l := 10.2  fmt.Println(k * l) ``
``Output1022.04 ``

In Go, division has different characteristics depending on the numeric type we’re dividing.

If we’re dividing integers, Go’s `/` operator performs floor division, where for the quotient x the number returned is the largest integer less than or equal to x.

If you run the following example of dividing `80 / 6`, you’ll receive `13` as the output and the data type will be `int`:

``package main  import (     "fmt" )  func main() {     m := 80     n := 6      fmt.Println(m / n) } ``
``Output13 ``

If the desired output is a float, you have to explicitly convert the values before dividing.

You can do this by wrapping your desired float type of `float32()` or `float64()` around your values:

``package main  import (     "fmt" )  func main() {     s := 80     t := 6     r := float64(s) / float64(t)     fmt.Println(r) } ``
``Output13.333333333333334 ``

## Modulo

The `%` operator is the modulo, which returns the remainder rather than the quotient after division. This is useful for finding numbers that are multiples of the same number.

Let’s look at an example of the modulo:

``o := 85 p := 15  fmt.Println(o % p) ``
``Output10 ``

To break this down, `85` divided by `15` returns the quotient of `5` with a remainder of `10`. Our program returns the value `10` here, because the modulo operator returns the remainder of a division expression.

To do modulus math with `float64` data types, you’ll use the `Mod` function from the `math` package:

``package main  import (     "fmt"     "math" )  func main() {     q := 36.0     r := 8.0      s := math.Mod(q, r)      fmt.Println(s) } ``
``Output4 ``

## Operator Precedence

In Go, as in mathematics, we need to keep in mind that operators will be evaluated in order of precedence, not from left to right or right to left.

If we look at the following mathematical expression:

``u = 10 + 10 * 5 ``

We may read it left to right, but multiplication will be done first, so if we were to print `u`, we would receive the following value:

``Output60 ``

This is because `10 * 5` evaluates to `50`, and then we add `10` to return `60` as the final result.

If instead we would like to add the value `10` to `10`, then multiply that sum by `5`, we use parentheses in Go just like we would in math:

``u := (10 + 10) * 5 fmt.Println(u) ``
``Output100 ``

One way to remember the order of operation is through the acronym PEMDAS:

Order Letter Stands for
1 P Parentheses
2 E Exponent
3 M Multiplication
4 D Division
6 S Subtraction

You may be familiar with another acronym for the order of operations, such as BEDMAS or BODMAS. Whatever acronym works best for you, try to keep it in mind when performing math operations in Go so that the results that you expect are returned.

## Assignment Operators

The most common assignment operator is one you have already used: the equals sign `=`. The `=` assignment operator assigns the value on the right to a variable on the left. For example, `v = 23` assigns the value of the integer `23` to the variable `v`.

When programming, it is common to use compound assignment operators that perform an operation on a variable’s value and then assign the resulting new value to that variable. These compound operators combine an arithmetic operator with the `=` operator. Therefore, for addition we’ll combine `+` with `=` to get the compound operator `+=`. Let’s see what that looks like:

``w := 5 w += 1 fmt.Println(w) ``
``Output6 ``

First, we set the variable `w` equal to the value of `5`, then we use the `+=` compound assignment operator to add the right number to the value of the left variable, and then assign the result to `w`.

Compound assignment operators are used frequently in the case of `for` loops, which you’ll use when you want to repeat a process several times:

``package main  import "fmt"  func main() {      values := []int{0, 1, 2, 3, 4, 5, 6}      for _, x := range values {          w := x          w *= 2          fmt.Println(w)     }  } ``
``Output0 2 4 6 8 10 12 ``

By using a `for` loop to iterate over the slice called `values`, you were able to automate the process of the `*=` operator that multiplied the variable `w` by the number `2` and then assigned the result back into the variable `w`.

Go has a compound assignment operator for each of the arithmetic operators discussed in this tutorial.

To add then assign the value:

``y += 1 ``

To subtract then assign the value:

``y -= 1 ``

To multiply then assign then value:

``y *= 2 ``

To divide then assign the value:

``y /= 3 ``

To return the remainder then assign the value:

``y %= 3 ``

Compound assignment operators can be useful when things need to be incrementally increased or decreased, or when you need to automate certain processes in your program.

## Conclusion

This tutorial covered many of the operators you’ll use with the integer and float numeric data types. You can learn more about different data types in Understanding Data Types in Go and How To Convert Data Types.

DigitalOcean Community Tutorials

## Stack Abuse: The Python Math Library

### Introduction

The Python Math Library provides us access to some common math functions and constants in Python, which we can use throughout our code for more complex mathematical computations. The library is a built-in Python module, therefore you don’t have to do any installation to use it. In this article, we will be showing example usage of the Python Math Library’s most commonly used functions and constants.

### Special Constants

The Python Math Library contains two important constants.

#### Pie

The first one is Pie (π), a very popular math constant. It denotes the ratio of circumference to diameter of a circle and it has a value of 3.141592653589793. To access it, we first import the Math Library as follows:

``import math   ``

We can then access this constant using `pi`:

``math.pi   ``

Output

``3.141592653589793   ``

You can use this constant to calculate the area or circumference of a circle. The following example demonstrates this:

``import math  radius = 2   print('The area of a circle with a radius of 2 is:', math.pi * (radius ** 2))   ``

Output

``The area of a circle with a radius of 2 is: 12.566370614359172   ``

We raised the value of the radius to a power of 2 then multiplied it by pie, per the area formula of πr2.

#### Euler’s Number

The Euler’s number (e), which is the base of natural logarithm is also defined in the Math library. We can access it as follows:

``math.e   ``

Output

``2.718281828459045   ``

The following example demonstrates how to use the above constant:

``import math  print((math.e + 6 / 2) * 4.32)   ``

Output

``24.702977498943074   ``

### Exponents and Logarithms

In this section, we will explore the Math library functions used to find different types of exponents and logarithms.

#### The exp() Function

The Python Math Library comes with the `exp()` function that we can use to calculate the power of `e`. For example, ex, which means the exponential of x. The value of `e` is 2.718281828459045.

The method can be used with the following syntax:

``math.exp(x)   ``

The parameter `x` can be a positive or negative number. If `x` is not a number, the method will return an error. Let us demonstrate the usage of this method with the help of an example:

``import math  # Initializing values an_int = 6   a_neg_int = -8   a_float = 2.00  # Pass the values to exp() method and print print(math.exp(an_int))   print(math.exp(a_neg_int))   print(math.exp(a_float))   ``

Output

``403.4287934927351   0.00033546262790251185   7.38905609893065   ``

We have declared three variables and assigned values with different numeric data types to them. We have then passed them to the `exp()` method to calculate their exponents.

We can also apply this method to inbuilt constants as demonstrated below:

``import math  print(math.exp(math.e))   print(math.exp(math.pi))   ``

Output

``15.154262241479262   23.140692632779267   ``

If you pass a non-numeric value to the method, it will generate an error, as demonstrated here:

``import math  print(math.exp("20"))   ``

Output

``Traceback (most recent call last):     File "C:/Users/admin/mathe.py", line 3, in <module>     print (math.exp("20")) TypeError: a float is required   ``

A TypeError has been generated as shown in the above output.

#### The log() Function

This function returns the logarithm of the specified number. The natural logarithm is computed with respect to the base `e`. The following example demonstrates the usage of this function:

``import math  print("math.log(10.43):", math.log(10.43))   print("math.log(20):", math.log(20))   print("math.log(math.pi):", math.log(math.pi))   ``

In the script above, we have passed numeric values with different data types to the method. We have also calculated the natural logarithm of the `pi` constant. The output looks like this:

Output

``math.log(10.43): 2.344686269012681   math.log(20): 2.995732273553991   math.log(math.pi): 1.1447298858494002   ``

#### The log10() Function

This method returns the base-10 logarithm of the specified number. For example:

``import math  # Returns the log10 of 50 print("The log10 of 50 is:", math.log10(50))   ``

Output

``The log10 of 50 is: 1.6989700043360187   ``

#### The log2() Function

This function calculates the logarithm of a number to base 2. For example:

``import math  # Returns the log2 of 16 print("The log2 of 16 is:", math.log2(16))   ``

Output

``The log2 of 16 is: 4.0   ``

#### The log(x, y) Function

This function returns the logarithm of x with y being the base. For example:

``import math  # Returns the log of 3,4 print("The log 3 with base 4 is:", math.log(3, 4))   ``

Output

``The log 3 with base 4 is: 0.6309297535714574   ``

#### The log1p(x) Function

This function calculates the logarithm(1+x), as demonstrated here:

``import math  print("Logarithm(1+x) value of 10 is:", math.log1p(10))   ``

Output

``Logarithm(1+x) value of 10 is: 2.3978952727983707   ``

### Arithmetic Functions

Arithmetic functions are used to represent numbers in various forms and perform mathematical operations on them. Some of the most common arithmetic functions are discussed below:

• `ceil()`: returns the ceiling value of the specified number.
• `fabs()`: returns the absolute value of the specified number.
• `floor()`: returs the floor value of the specified number.
• `gcd(a, b)`: returns the greatest common divisor of `a` and `b`.
• `fsum(iterable)`: returns the sum of all elements in an iterable object.
• `expm1()`: returns (e^x)-1.
• `exp(x)-1`: when the value of x is small, calculating `exp(x)-1` may lead to a significant loss in precision. The `expm1(x)` can return the output in with full precision.

The following example demonstrates the use of the above functions:

``import math  num = -4.28   a = 14   b = 8   num_list = [10, 8.25, 75, 7.04, -86.23, -6.43, 8.4]   x = 1e-4 # A small value of x  print('The number is:', num)   print('The floor value is:', math.floor(num))   print('The ceiling value is:', math.ceil(num))   print('The absolute value is:', math.fabs(num))   print('The GCD of a and b is: ' + str(math.gcd(a, b)))   print('Sum of the list elements is: ' + str(math.fsum(num_list)))   print('e^x (using function exp()) is:', math.exp(x)-1)   print('e^x (using function expml()) is:', math.expm1(x))   ``

Output

``The number is: -4.28   The floor value is: -5   The ceiling value is: -4   The absolute value is: 4.28   The GCD of a and b is: 2   Sum of the list elements is: 16.029999999999998   e^x (using function exp()) is: 0.0001000050001667141   e^x (using function expml()) is: 0.00010000500016667084   ``

Other math functions include the following:

• `pow()`: takes two float arguments and raises the first argument to the second argument and returns the result. For example, `pow(2,2)` is equivalent to `2**2`.
• `sqrt()`: returns the square root of the specified number.

These methods can be used as demonstrated below:

Power:

``math.pow(3, 4)   ``

Output

``81.0   ``

Square Root:

``math.sqrt(81)   ``

Output

``9.0   ``

### Trigonometric Functions

The Python Math module supports all the trigonometric functions. Some of them have been enlisted below:

• `sin(a)`: Returns the sine of “a” in radians
• `cos(a)`: Returns the cosine of “a” in radians
• `tan(a)`: Returns the tangent of “a” in radians
• `asin(a)`: Returns the inverse of sine. Also, there are “atan” and “acos”.
• `degrees(a)`: Converts an angle “a” from radian to degrees.
• `radians(a)`: Converts angle “a” from degrees to radian.

Consider the following example:

``import math  angle_In_Degrees = 62   angle_In_Radians = math.radians(angle_In_Degrees)  print('The value of the angle is:', angle_In_Radians)   print('sin(x) is:', math.sin(angle_In_Radians))   print('tan(x) is:', math.tan(angle_In_Radians))   print('cos(x) is:', math.cos(angle_In_Radians))   ``

Output

``The value of the angle is: 1.0821041362364843   sin(x) is: 0.8829475928589269   tan(x) is: 1.8807264653463318   cos(x) is: 0.46947156278589086   ``

Note that we first converted the value of the angle from degrees to radians before performing the other operations.

### Type Conversion

You can convert a number from one type to another. This process is known as “coercion”. Python can internally convert a number from one type to another when an expression has values of mixed types. The following example demonstrates this:

``3 + 5.1   ``

Output

``8.1   ``

In the above example, the integer 3 has been coerced to 3.0, a float, for addition operation and the result is also a float.

However, it is sometimes necessary for you to explicitly coerce a number from one type to another in order to meet the requirements of a function parameter or an operator. This can be done using various Python’s built-in functions. For example, to convert an integer to a float, we have to call the `float()` function as shown below:

``a = 12   b = float(a)   print(b)   ``

Output

``12.0   ``

The integer has been converted to a float. A float can be converted to an integer as follows:

``a = 12.65   b = int(a)   print(b)   ``

Output

``12   ``

The float has been converted to an integer by removing the fractional part and keeping the base number. Note that when you convert a value to an int in this way, it will be truncated rather than being rounded off.

### Conclusion

The Python Math Library provides us with functions and constants that we can use to perform arithmetic and trigonometric operations in Python. The library comes installed in Python, hence you are not required to perform any additional installation in order to be able to use it. For more info you can find the official documentation here.

Planet Python