11

Currently, math.Pow() and math.sqrt take float64 type arguments.

Do we have equivalent functions that take int type arguments?

callmekatootie
  • 10,989
  • 15
  • 69
  • 104

4 Answers4

5

If your return value is a float, you can use Ceil or Floor from the math package and then convert it to an int.

n := 5.5
o := math.Floor(n)
p := int(math.Pow(o, 2))

fmt.Println("Float:", n)
fmt.Println("Floor:", o)
fmt.Println("Square:", p)

5.5
5
25

Keep in mind that Floor still returns a float64, so you will still want to wrap it in int()

3

just create a float64 object using the int value. Example if int = 10.

var x float64 = 10
var b = math.Pow(2, x) 
medium
  • 4,136
  • 16
  • 55
  • 66
0

There are fast approximate algorithms described elsewhere on SO, such as this one. If performance is important, porting one of the C algorithms to Go might be worth the effort.

Community
  • 1
  • 1
Rick-777
  • 9,714
  • 5
  • 34
  • 50
-3

What you can do is type-cast a float to your value.

int a=10,b=2;
math.Pow(float(a),float(b));