pseudo-python icon indicating copy to clipboard operation
pseudo-python copied to clipboard

Pow operator produces incorrect Go translation

Open ns-cweber opened this issue 8 years ago • 3 comments

Python's pow operator (x**2) produces math.Pow(x, 2) in Go; however, in Go, math.Pow() only accepts floats, but in Python, ** handles ints as well as floats. This means the Python program:

x = 2
print(x**2)

Translates to

// package decl and imports elided
func main() {
	x := 2 // int
	fmt.Println(math.Pow(x, 2))
}

Which fails to compile with error: ./foo.go:10: cannot use x (type int) as type float64 in argument to math.Pow

ns-cweber avatar Jan 09 '17 17:01 ns-cweber

What would be idiomatic in Go: to call bigint Exp ? The other posibillity is to generate a PowInt function for cases like this.

alehander92 avatar Jan 09 '17 19:01 alehander92

I would inline int(math.Pow(float64(a), float64(b)), or a custom PowInt() if math.Pow() isn't very performant for integers. I would use bigint if I was concerned about overflow. I'm not sure how you generalize this for all applications--maybe you just always use bigint and take the perf hit in all cases?

ns-cweber avatar Jan 09 '17 21:01 ns-cweber

That would be the alpha versions choice, however later versions might add support for type annotations which could signify bigint

alehander92 avatar Jan 10 '17 15:01 alehander92