Compute the Power of a Number in Go
In this tutorial, we will learn how to compute the power of a number in Go. We will cover the basic concept of exponentiation and implement a function to perform the calculation.
What is Exponentiation
Exponentiation is a mathematical operation that involves raising a base number to the power of an exponent. For example, 2 raised to the power of 3 is 23 = 8.
Syntax
The syntax to compute the power of a number in Go is:
import (
"fmt"
"math"
)
func power(base float64, exponent float64) float64 {
return math.Pow(base, exponent)
}
Example 1: Computing the power of a number
We can create a function to compute the power of a given base and exponent using the math.Pow function.
For example,
- Import the
fmt
andmath
packages. - Define a function named
power
that takes two parametersbase
andexponent
of typefloat64
. - Use the
math.Pow
function to raise the base to the power of the exponent. - Return the result.
- In the main function, call the
power
function with sample values and print the result.
Go Program
package main
import (
"fmt"
"math"
)
func power(base float64, exponent float64) float64 {
return math.Pow(base, exponent)
}
func main() {
// Sample values
base := 2.0
exponent := 3.0
// Compute the power
result := power(base, exponent)
// Print the result
fmt.Printf("%.2f raised to the power of %.2f is %.2f\n", base, exponent, result)
}
Output
2.00 raised to the power of 3.00 is 8.00