加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

golang中的奇怪的pow实现

发布时间:2020-12-16 09:24:50 所属栏目:大数据 来源:网络整理
导读:我刚刚遇到 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 } //...} 不是这
我刚刚遇到 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
        }
    //...
}

不是这种情况y> 0部分复杂吗?我会回来0.或者我错过了什么?

解决方法

有两种类型的零,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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读