Calculate x^y – math.Pow() Function in Go (Golang)

Golang math.Pow() function is  “used to calculate x to the power y”. It accepts two arguments of type float64: the base and the exponent, and returns a float64 value as 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).

That’s it.

Related posts

Golang math.Ceil()

Golang math.Min()

Golang math.Floor()

Golang math.Round()

Golang math.Mod()

Leave a Comment