8

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

Do we have equivalent functions that take int type arguments?

callmekatootie
  • 10,272
  • 13
  • 63
  • 98

4 Answers4

2

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()

1

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

var x float64 = 10
var b = math.Pow(2, x) 
medium
  • 3,708
  • 14
  • 50
  • 63
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
  • 8,290
  • 5
  • 31
  • 47
-1

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

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