find the logarithm of a number in go

In Go, you can find the logarithm of a number using the math package's Log10 or Log2 functions, which respectively calculate the base-10 or base-2 logarithm of a given floating-point number. The following code snippet calculates the base-10 logarithm of a number:

main.go
package main

import (
    "fmt"
    "math"
)

func main() {
    x := 100.0
    y := math.Log10(x)
    fmt.Printf("log10(%f) = %f\n", x, y)
}
142 chars
13 lines

Alternatively, you can also calculate the natural logarithm (ln) of a number using the math package's Log function:

main.go
package main

import (
    "fmt"
    "math"
)

func main() {
    x := 100.0
    y := math.Log(x)
    fmt.Printf("ln(%f) = %f\n", x, y)
}
137 chars
13 lines

Note that any logarithmic function is the inverse of an exponential function, so you can also calculate the logarithm of a number using the exponential function in combination with the logarithmic base of your choice. For example:

main.go
package main

import (
    "fmt"
    "math"
)

func main() {
    x := 100.0
    base := 2.0
    y := math.Log(x) / math.Log(base)
    fmt.Printf("log(%f, %f) = %f\n", base, x, y)
}
181 chars
14 lines

gistlibby LogSnag