Finding the Decimal Logarithm of Given Number in Golang


In mathematics, logarithm is an operation that tells us how many times a given number can be divided by a certain value to get a result. Decimal logarithm is a special type of logarithm in which the base is 10. In Golang, the math package provides the Log10 function to find the decimal logarithm of a given number.

Syntax

The syntax for the Log10 function in Golang is as follows −

func Log10(x float64) float64

The Log10 function takes a single argument of type float64 and returns the decimal logarithm of that number.

Example 1

Let's say we want to find the decimal logarithm of the number 100. We can do this using the Log10 function as follows −

package main

import (
   "fmt"
   "math"
)

func main() {
   x := 100.0
   result := math.Log10(x)
   fmt.Printf("Log10(%v) = %v\n", x, result)
}

Output

Log10(100) = 2

In the above code, we first import the "fmt" and "math" packages, and then declare a variable x and initialize it to the value of 100. We then call the Log10 function from the math package with x as its argument, and store the result in a variable named result. Finally, we print the value of result using the fmt package.

Example 2

Let's try to find the decimal logarithm of a decimal number such as 0.01. We can do this as follows −

package main

import (
   "fmt"
   "math"
)

func main() {
   x := 0.01
   result := math.Log10(x)
   fmt.Printf("Log10(%v) = %v\n", x, result)
}

Output

Log10(0.01) = -2

In the above code, we first import the "fmt" and "math" packages, and then declare a variable x and initialize it to the value of 0.01. We then call the Log10 function from the math package with x as its argument, and store the result in a variable named result. Finally, we print the value of result using the fmt package.

Example 3

Let's try to find the decimal logarithm of a negative number. We can do this as follows −

package main

import (
   "fmt"
   "math"
)

func main() {
   x := -10.0
   result := math.Log10(x)
   fmt.Printf("Log10(%v) = %v\n", x, result)
}

Output

Log10(-10) = NaN

In the above code, we first import the "fmt" and "math" packages, and then declare a variable x and initialize it to the value of -10. We then call the Log10 function from the math package with x as its argument, and store the result in a variable named result. Finally, we print the value of result using the fmt package.

Conclusion

The Log10 function provided by the math package in Golang is a useful tool for finding the decimal logarithm of a given number. It can be used to perform a wide range of mathematical operations that involve logarithms. However, it's important to note that the function may return NaN (Not a Number) if the input is negative or zero.

Updated on: 12-Apr-2023

186 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements