Welcome To Golang By Example

Log of number in Go (Golang)

Overview

In this tutorial, we will see three types of logarithm possible

Natural logarithm

math package of GO provides a Log method that can be used to get the natural logarithm of a number

Below is the signature of the function. It takes input as a float64 number and returns a float64.

func Log(x float64) float64

Also some special cases of Logb function are

Code

package main

import (
    "fmt"
    "math"
)

func main() {
    res := math.Log(4)
    fmt.Println(res)

    res = math.Log(10.2)
    fmt.Println(res)

    res = math.Log(-10)
    fmt.Println(res)
}

Output:

1.3862943611198906
2.322387720290225
NaN

Binary Exponent Log (log e)

math package of golang provides a Logb method that can be used to get the binary exponent of a number

Below is the signature of the function. It takes input as a float64 number and returns a float64.

func Logb(x float64) float64

Also some special cases of Logb function are

Code

package main

import (
    "fmt"
    "math"
)

func main() {
    res := math.Logb(4)
    fmt.Println(res)

    res = math.Logb(10.2)
    fmt.Println(res)

    res = math.Logb(-10)
    fmt.Println(res)
}

Output:

2
3
3

Binary Log (log 2)

math package of golang provides a Log2 method that can be used to get the binary logarithm or log to base 2 of a number

Below is the signature of the function. It takes input as a float64 number and returns a float64.

Also some special cases of Log2 function are

Code

package main

import (
    "fmt"
    "math"
)

func main() {
    res := math.Log2(4)
    fmt.Println(res)

    res = math.Log2(10.2)
    fmt.Println(res)

    res = math.Log2(-10)
    fmt.Println(res)
}

Output:

2
3.321928094887362
NaN

Decimal Log (log 10)

math package of go provides a Log10 method that can be used to get the decimal logarithm or log to base 10 of a number

Below is the signature of the function. It takes input as a float64 number and returns a float64.

func Log10(x float64) float64

Also some special cases of Log10 function are

Code

package main

import (
    "fmt"
    "math"
)

func main() {
    res := math.Log10(100)
    fmt.Println(res)

    res = math.Log10(10)
    fmt.Println(res)

    res = math.Log10(-10)
    fmt.Println(res)
}

Output:

2
1
NaN