<< Back to GO
Golang Math Module: math.Abs, Pow
Perform mathematical computations with the math module. Call math.Abs and math.Pow.Math. Languages often have built-in math methods. With Go we import the math module. This provides commonly-used methods like Abs and Pow.
Float64. Math methods here operate on the float64 numeric type. So we cannot use an int directly with them—we must cast it first. This requires some extra complexity.
Math.Abs. Let us begin with Abs. We import the math module in the import-statement at the top. Next we introduce the "negative" integer.
Then: We convert the "negative" number to a float64 and pass that to the math.Abs method. This returns a positive number.
Golang program that uses math.Abs, float64
package main
import (
"fmt"
"math"
)
func main() {
negative := -10
fmt.Println(negative)
// Use math.Abs to convert to a positive number.
// ... We first convert to a float64.
result := math.Abs(float64(negative))
fmt.Println(result)
}
Output
-10
10
Pow, compute exponents. Pow raises one number to another. Here we compute the cube of 2, which is 8. We can also square numbers (with a second argument of 2) or use higher powers.
Golang program that uses math.Pow
package main
import (
"fmt"
"math"
)
func main() {
// This can handle ints.
result := math.Pow(2, 3)
fmt.Println(result)
}
Output
8
Max, Min. The math.Max and math.Min methods both receive two float64 values. Max returns the higher of the two. Min returns the lower.
Note: If both values are equal, the result is that value. A separate comparison must determine this case.
Golang program that uses Max, Min
package main
import (
"fmt"
"math"
)
func main() {
small := float64(3)
large := float64(40)
// Get the larger of the two numbers.
max := math.Max(small, large)
fmt.Println(max)
// Get the smaller value.
min := math.Min(small, large)
fmt.Println(min)
}
Output
40
3
Floor. The floor is beneath us. With math.Floor, a number with a fractional part is always reduced so the fractional part does not exist. Both negative and positive numbers are reduced.
Golang program that uses math.Floor
package main
import (
"fmt"
"math"
)
func main() {
value1 := 1.23
fmt.Println(value1)
fmt.Println(math.Floor(value1))
value2 := 2.99
fmt.Println(value2)
fmt.Println(math.Floor(value2))
value3 := -1.1
fmt.Println(value3)
fmt.Println(math.Floor(value3))
}
Output
1.23
1
2.99
2
-1.1
-2
Signbit. This math method returns a bool. If the number is negative (has a sign bit) then Signbit returns true. For positive numbers, it returns false.
Golang program that uses math.Signbit
package main
import (
"fmt"
"math"
)
func main() {
value1 := float64(1)
negative := math.Signbit(value1)
fmt.Println(negative)
value2 := float64(-1)
negative = math.Signbit(value2)
fmt.Println(negative)
value3 := float64(0)
negative = math.Signbit(value3)
fmt.Println(negative)
}
Output
false
true
false
Odd, even. An int has a parity: this is whether it is odd or even. To compute parity, we use a modulo division. We can define "odd" as "not even."
Odd, Even
Fibonacci. In the Fibonacci sequence, each number is equal to the preceding two numbers. This sequence occurs often in the natural world. It has many uses.
Fibonacci
A summary. Many math methods are available in the math package. We can implement math methods directly, with imperative statements. But this often leads to unneeded complexity.
Related Links:
- Golang strconv, Convert Int to String
- Golang Odd and Even Numbers
- Golang Recover Built In: Handle Errors, Panics
- Learn Go Language Tutorial
- Golang html template Example
- Golang http.Get Examples: Download Web Pages
- Golang container list Example (Linked List)
- Golang base64 Encoding Example: EncodeToString
- Golang os exec Examples: Command Start and Run
- Golang String Between, Before and After
- Golang os.Remove: Delete All Files in Directory
- Golang First Words in String
- Golang flag Examples
- Golang Regexp Find Examples: FindAllString
- Golang Regexp Examples: MatchString, MustCompile
- Golang Index, LastIndex: strings Funcs
- Golang Compress GZIP Examples
- Golang Interface Example
- Golang 2D Slices and Arrays
- Golang Sscan, Sscanf Examples (fmt)
- Top 41 Go Programming (Golang) Interview Questions (2021)
- Golang Padding String Example (Right or Left Align)
- Golang Equal String, EqualFold (If Strings Are the Same)
- Golang map Examples
- Golang Map With String Slice Values
- Golang Array Examples
- Golang Remove Duplicates From Slice
- Golang If, Else Statements
- Golang ParseInt Examples: Convert String to Int
- Golang Strings
- Golang strings.Map func
- Golang bufio.ScanBytes, NewScanner (Read Bytes in File)
- Golang Built In Functions
- Golang bytes.Buffer Examples (WriteString, Fprintf)
- Golang Bytes: Slices and Methods
- Golang Caesar Cipher Method
- Golang Chan: Channels, Make Examples
- Golang Math Module: math.Abs, Pow
- Golang Reverse String
- Golang Struct Examples: Types and Pointers
- Golang path and filepath Examples (Base, Dir)
- Golang Substring Examples (Rune Slices)
- Golang Suffixarray Examples: New, Lookup Benchmark
- Golang switch Examples
- Golang Convert Map to Slice
- Golang Convert Slice to String: int, string Slices
- Golang Const, Var Examples: Iota
- Golang ROT13 Method
- Golang strings.Contains and ContainsAny
- Golang rand, crypto: Random Number Generators
- Golang String Literal Examples (Repeat Method)
- Golang ToLower, ToUpper String Examples
- Golang Trim, TrimSpace and TrimFunc Examples
- Golang Join Examples (strings.Join)
- Golang Len (String Length)
- Golang Convert String to Rune Slice (append)
- Golang JSON Example: Marshal, Unmarshal
- Golang Replace String Examples: Replacer, NewReplacer
- Golang nil (Cannot Use nil as Type)
- Golang Slice Examples
- Golang ListenAndServe Examples (HandleFunc)
- Golang Fibonacci Sequence Example
- Golang Time: Now, Parse and Duration
- Golang bits, OnesCount (Get Bitcount From Int)
- Golang Fprint, Fprintf and Fprintln Examples (fmt)
- Golang Func Examples
- Golang csv Examples
- Golang Fields and FieldsFunc
- Golang unicode.IsSpace (If Char Is Whitespace)
- Golang fmt.Println Examples
- Golang for Loop Examples: Foreach and While
- Golang ioutil.WriteFile, os.Create (Write File to Disk)
- Golang File Handling
- Golang range: Slice, String and Map
- Golang Readdir Example (Get All Files in Directory)
- Golang Sort Slice: Len, Less, Swap in Interface
- Golang Get Lines in File (String Slice)
- Golang Split Examples (SplitAfter, SplitN)
Related Links
Adjectives
Ado
Ai
Android
Angular
Antonyms
Apache
Articles
Asp
Autocad
Automata
Aws
Azure
Basic
Binary
Bitcoin
Blockchain
C
Cassandra
Change
Coa
Computer
Control
Cpp
Create
Creating
C-Sharp
Cyber
Daa
Data
Dbms
Deletion
Devops
Difference
Discrete
Es6
Ethical
Examples
Features
Firebase
Flutter
Fs
Git
Go
Hbase
History
Hive
Hiveql
How
Html
Idioms
Insertion
Installing
Ios
Java
Joomla
Js
Kafka
Kali
Laravel
Logical
Machine
Matlab
Matrix
Mongodb
Mysql
One
Opencv
Oracle
Ordering
Os
Pandas
Php
Pig
Pl
Postgresql
Powershell
Prepositions
Program
Python
React
Ruby
Scala
Selecting
Selenium
Sentence
Seo
Sharepoint
Software
Spellings
Spotting
Spring
Sql
Sqlite
Sqoop
Svn
Swift
Synonyms
Talend
Testng
Types
Uml
Unity
Vbnet
Verbal
Webdriver
What
Wpf