我刚遇到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
}
//...
}
case y > 0
部分不是很复杂吗?我会回来0.或者我错过了什么?
答案 0 :(得分:4)
有两种类型的零,+0
和-0
。 Pow(-0,1)
的返回值应为-0
而不是+0
在golang中创建-0
,请使用math.Copysign
。
x := math.Copysign(0, -1)
if x == 0 {
fmt.Println("x is zero")
}
fmt.Println("x ** 3 is", math.Pow(x, 3))
上述代码的输出是
x is zero
x ** 3 is -0
您可以在Go Playground
中查看为什么我们必须区分+0
和-0
,请参阅:
https://softwareengineering.stackexchange.com/questions/280648/why-is-negative-zero-important
答案 1 :(得分:1)
答案在函数的内联文档中,在案例y > 0
的情况下,函数输出如下:
Pow(±0, y) = ±0 for y an odd integer > 0
Pow(±0, y) = +0 for finite y > 0 and not an odd integer
所以该函数只会返回0
(+0)
,就像您在x=0