英文:
Strange pow implementation in golang
问题
我刚刚看到了golang中的Pow实现:
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。或者我漏掉了什么吗?
英文:
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?
答案1
得分: 4
有两种类型的零,+0 和 -0。Pow(-0,1) 的返回值应该是 -0 而不是 +0。
在 Go 语言中,要创建 -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
英文:
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
答案2
得分: 1
答案在函数的内联文档中,对于情况 y > 0,函数的输出如下:
当 y 是一个大于 0 的奇整数时,Pow(±0, y) = ±0
当 y 是一个有限的大于 0 且不是奇整数时,Pow(±0, y) = +0
所以在 x=0 的情况下,函数只会返回 0 (+0),就像你所说的那样。
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论