在Go语言中,将-float64(0)与float64(0)区分开来的标志是什么?

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

Distinguishing sign of zero : -float64(0) from float64(0) in Go

问题

我想以一种不丢失符号信息的方式对浮点数进行序列化。具体来说,我想区分IEEE-754负零和普通零。

语言规范中说

> 除以零的浮点数运算结果在IEEE-754标准之外是未指定的;是否发生运行时恐慌是与实现相关的。

这意味着我不能这样做:

n == 0 && (float64(1) / n) < 0

我尝试了math.Copysignmath.Signbit,它们说

> func Signbit(x float64) bool
>
> 如果x为负或负零,则Signbit返回true

但是

n == 0 && math.Signbit(n)

对于

n := -float64(0)

似乎不起作用。

有什么想法吗?

编辑:

我提交了问题2196来跟踪我认为的一个令人困惑的差异,即

nz := -float64(0)

pz := float64(0)
nz := -pz

如peterSO所建议的。

英文:

I want to serialize a floating point in such a way that sign info is not lost. Specifically, I would like to distinguish IEEE-754 negative zero from regular zero.

The language spec says

> The result of a floating-point division by zero is not specified beyond the IEEE-754 standard; whether a run-time panic occurs is implementation-specific.

which suggests that I cannot do

n == 0 && (float64(1) / n) < 0

and I tried math.Copysign and math.Signbit which says

> func Signbit(x float64) bool
>
> Signbit returns true if x is negative or negative zero.

but

n == 0 && math.Signbit(n)

doesn't seem to work for

n := -float64(0)

Any ideas?

EDIT:

I filed issue 2196 to track what I think is a confusing difference between

nz := -float64(0)

and

pz := float64(0)
nz := -pz

as suggested by peterSO.

答案1

得分: 3

我无法通过在源代码中直接输入来使go playground(http://golang.org/doc/play/)生成-0;我猜测编译器会将其转换为0。

然而,我可以通过以下方式生成-0:

fmt.Println(0);
fmt.Println(-0);
hmm := -1 / math.Inf(1);
fmt.Println(math.Signbit(hmm));
fmt.Println(hmm);

输出结果:

0
0
true
-0
英文:

I couldn't get the go playground ( http://golang.org/doc/play/ ) to generate a -0 from literally typing it in source; I'd speculate the compiler converts it to 0.

However, I could generate a -0 like this:

fmt.Println(0);
fmt.Println(-0);
hmm := -1 / math.Inf(1);
fmt.Println(math.Signbit(hmm));
fmt.Println(hmm);

Prints:

0
0
true
-0

答案2

得分: 3

package main

import (
"fmt"
"math"
)

func main() {
pz := float64(0)
nz := -pz
fmt.Println(pz, math.Signbit(pz), nz, math.Signbit(nz))
if n := nz; n == 0 && math.Signbit(n) {
fmt.Println("n is negative zero:", n)
}
}

输出:

0 false -0 true
n is negative zero: -0
英文:
package main

import (
	"fmt"
	"math"
)

func main() {
	pz := float64(0)
	nz := -pz
	fmt.Println(pz, math.Signbit(pz), nz, math.Signbit(nz))
	if n := nz; n == 0 && math.Signbit(n) {
		fmt.Println("n is negative zero:", n)
	}
}

Output:

0 false -0 true
n is negative zero: -0

huangapple
  • 本文由 发表于 2011年8月29日 05:37:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/7224132.html
匿名

发表评论

匿名网友

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

确定