Reputation: 23134
I just came across the Pow implementation in golang:
func Pow(x, y float64) float64 {
// ...
case x == 0:
switch {
case y < 0:
if isOddInt(y) {
return Copysign(Inf(1), x)
}
return Inf(1)
case y > 0:
if isOddInt(y) {
return x
}
return 0
}
//...
}
Isn't the case y > 0
part over complicated? I would just return 0. Or did I miss something?
Upvotes: 4
Views: 546
Reputation: 12100
there are two types of zero's, +0
and -0
. return value of Pow(-0,1)
should be -0
not +0
to create -0
in golang, use math.Copysign
.
x := math.Copysign(0, -1)
if x == 0 {
fmt.Println("x is zero")
}
fmt.Println("x ** 3 is", math.Pow(x, 3))
the output of above code is
x is zero
x ** 3 is -0
you can check it in Go Playground
why we have to distinguish +0
and -0
, see:
https://softwareengineering.stackexchange.com/questions/280648/why-is-negative-zero-important
Upvotes: 4
Reputation: 10575
The answer is in the inline documentation for the function, in the case case y > 0
then the function output is as follows:
Pow(±0, y) = ±0 for y an odd integer > 0
Pow(±0, y) = +0 for finite y > 0 and not an odd integer
so the function will only return 0
(+0)
like you say in the case that x=0
Upvotes: 1