Home > Net >  Golang | Is it possible to calculate a power value without using math library?
Golang | Is it possible to calculate a power value without using math library?

Time:06-02

I am wondering how can we calculate a power value withing using math library?

I have checked the method for calculating a power value that most of the ways are using the math library to achieve (i.e., math.Pow).

For example, if we wanna calculate 3^2, we can do the way like 3**2 in Python, so I am curious is it possible to do a similar way like Python via math symbols to calculate it in Go?

Thank you!

CodePudding user response:

If the numbers are integer, then this should work:

package main

import (
    "fmt"
)

func main() {
    number := 4
    power := 5
    result := 1

    for power != 0 {
        result = result * number
        power = power - 1
    }
    fmt.Println(result)
}

CodePudding user response:

There's no Go operator ("math symbols") to do this, though if the exponent is constant you could of course just write x*x for x^2, or x*x*x for x^3.

If the exponent is not constant but is an integer, a simple way to calculate n^exp is to use repeated multiplication, something like this:

func pow(n float64, exp int) float64 {
    if exp < 0 { // handle negative exponents
        n = 1 / n
        exp = -exp
    }
    result := 1.0
    for i := 0; i < exp; i   {
        result *= n
    }
    return result
}

That said, I'm not exactly sure why you'd want to avoid math.Pow -- it's in the standard library and it's faster and more general.

  •  Tags:  
  • go
  • Related