负零字面量在golang中

huangapple go评论103阅读模式
英文:

Negative zero literal in golang

问题

IEEE754支持负零。但是这段代码

  1. a := -0.0
  2. fmt.Println(a, 1/a)

输出

  1. 0 +Inf

而我期望的是

  1. -0 -Inf

其他基于IEEE754的编程语言允许你创建负零字面量

Java:

  1. float a = -0f;
  2. System.out.printf("%f %f", a, 1/a); // 输出 "-0.000000 -Infinity"

C#:

  1. var a = -0d;
  2. Console.WriteLine(1/a); // 输出 "-Infinity"

Javascript:

  1. var a = -0;
  2. console.log(a, 1/a); // 输出 "0 -Infinity"

但是我在Go中找不到相应的写法。

在Go中如何表示负零字面量?

英文:

IEEE754 supports the negative zero.
But this code

  1. a := -0.0
  2. fmt.Println(a, 1/a)

outputs

  1. 0 +Inf

where I would have expected

  1. -0 -Inf

Other languages whose float format is based on IEEE754 let you create negative zero literals

Java :

  1. float a = -0f;
  2. System.out.printf("%f %f", a, 1/a); // outputs "-0,000000 -Infinity"

C# :

  1. var a = -0d;
  2. Console.WriteLine(1/a); // outputs "-Infinity"

Javascript :

  1. var a = -0;
  2. console.log(a, 1/a);​ // logs "0 -Infinity"

But I couldn't find the equivalent in Go.

How do you write a negative zero literal in go ?

答案1

得分: 11

有一个已注册的问题

并且它恰好提供了一种解决方案:

  1. a := math.Copysign(0, -1)

这并不是很糟糕,因为它显然是指由IEEE754定义的标准copysign函数。

但这意味着你需要导入一个包,对于(尽管是次要且罕见的)需求来说,这仍然显得太重了。

英文:

There is a registered issue.

And it happens to give a kind of solution :

  1. a := math.Copysign(0, -1)

It's not so bad as it obviously refers to the standard copysign function defined by IEEE754.

But this means you need to import a package and this still looks much too heavy for the (admittedly minor and rare) need.

答案2

得分: 6

package main

import (
"fmt"
"math"
)

func main() {
a := 1. / math.Inf(-1)
fmt.Println(a, 1/a)
}

英文:
  1. package main
  2. import (
  3. "fmt"
  4. "math"
  5. )
  6. func main() {
  7. a := 1. / math.Inf(-1)
  8. fmt.Println(a, 1/a)
  9. }

(Also here)


Output:

  1. -0 -Inf

答案3

得分: 0

我刚刚尝试了一下,对我来说似乎可以工作。

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func main() {
  6. zero := float64(0)
  7. neg_zero := -zero
  8. fmt.Println(zero, neg_zero)
  9. }

尽管当我执行neg_zer0 := - float64(0)时,它并不像预期的那样工作。

英文:

I just tried out this and it seems to work for me .

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func main() {
  6. zero := float64(0)
  7. neg_zero := -zero
  8. fmt.Println(zero, neg_zero)
  9. }

Though it does not work as expected when I do neg_zer0 := - float64(0)

huangapple
  • 本文由 发表于 2012年12月10日 23:46:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/13804255.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定