What is the math.Pow() Function in Golang

The math.Pow() in Golang is a built-in function that returns the result of raising a given base to a given exponent. It accepts two arguments of type float64: the base and the exponent. It returns a float64 value is the result of raising the base to the exponent power.

Syntax

func Pow(x, y float64) float64

Parameters

It takes two arguments of float64 data type, which has IEEE-754 64-bit floating-point numbers.

Return value

The Pow() function returns x**y, the base-x exponential of y.

Special cases

Pow(x, ±0) = 1 for any x
Pow(1, y) = 1 for any y
Pow(x, 1) = x for any x
Pow(NaN, y) = NaN
Pow(x, NaN) = NaN
Pow(±0, y) = ±Inf for y an odd integer < 0
Pow(±0, -Inf) = +Inf
Pow(±0, +Inf) = +0
Pow(±0, y) = +Inf for finite y < 0 and not an odd integer
Pow(±0, y) = ±0 for y an odd integer > 0
Pow(±0, y) = +0 for finite y > 0 and not an odd integer
Pow(-1, ±Inf) = 1
Pow(x, +Inf) = +Inf for |x| > 1
Pow(x, -Inf) = +0 for |x| > 1
Pow(x, +Inf) = +0 for |x| < 1
Pow(x, -Inf) = +Inf for |x| < 1
Pow(+Inf, y) = +Inf for y > 0
Pow(+Inf, y) = +0 for y < 0
Pow(-Inf, y) = Pow(-0, -y)
Pow(x, y) = NaN for finite x < 0 and finite non-integer y

Example 1

Use the math.Pow() function to calculate x to the power y in Go.

package main

import (
  "fmt"
  "math"
)

func main() {
  var x float64
  x = math.Pow(2, 3)
  fmt.Println(x)
}

Output

8

Example 2

package main

import (
  "fmt"
  "math"
)

func main() {
 base := 3.0
 exponent := 4.0
 result := math.Pow(base, exponent)
 fmt.Printf("%v ^ %v = %v \n", base, exponent, result)
}

Output

3 ^ 4 = 81

Additionally, be aware of the limitations of floating-point arithmetic, especially when dealing with very large or very small numbers.

Error Handling

The math.Pow() function will throw an error if the two input parameters, x or y, are not numbers.

The compiler will issue an error if the function is called without an argument (the input value, x or y).

FAQ

What is the math.Pow() function in Go?

Golang math.Pow() function takes two arguments, the base and the exponent, and returns the result of raising the base to the exponent power.

What are the arguments and return value of the math.Pow() function?

The math.Pow() function takes two arguments, both of type float64, and returns a float64 value, which results from raising the base to the exponent power.

How is the math.Pow() function used in programming?

The math.Pow() function is used in programming for computing exponentials and powers.

Conclusion

Golang math.Pow() is a built-in function that takes two float64 arguments, the base and exponent, and returns the result of raising the base to the exponent power.

Leave a Comment