负零字面量在golang中

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

Negative zero literal in golang

问题

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

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

输出

0 +Inf

而我期望的是

-0 -Inf

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

Java:

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

C#:

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

Javascript:

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

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

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

英文:

IEEE754 supports the negative zero.
But this code

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

outputs

0 +Inf

where I would have expected

-0 -Inf

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

Java :

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

C# :

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

Javascript :

​var a = -0;
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

有一个已注册的问题

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

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

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

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

英文:

There is a registered issue.

And it happens to give a kind of solution :

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)
}

英文:
package main

import (
        "fmt"
        "math"
)

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

(Also here)


Output:

-0 -Inf

答案3

得分: 0

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

package main

import (
	"fmt"
)

func main() {
	zero := float64(0)
	neg_zero := -zero
	fmt.Println(zero, neg_zero)
}

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

英文:

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

package main

import (
	"fmt"
	)

func main() {
	zero := float64(0)
	neg_zero := -zero
	fmt.Println(zero, neg_zero)
}

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:

确定