[英]Distinguishing sign of zero : -float64(0) from float64(0) in Go
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. 具体来说,我想区分IEEE-754负零和常规零。
The language spec says 语言规范说
The result of a floating-point division by zero is not specified beyond the IEEE-754 standard; 除了IEEE-754标准之外,没有规定浮点除零的结果。 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 我试过math.Copysign
和math.Signbit
说
func Signbit(x float64) bool
Signbit
returnstrue
if x is negative or negative zero. 如果x为负或负零,则Signbit
返回true
。
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 我提交了问题2196,以追踪我认为之间令人困惑的区别
nz := -float64(0)
and 和
pz := float64(0)
nz := -pz
as suggested by peterSO. 正如彼得斯所建议的那样。
I couldn't get the go playground ( http://golang.org/doc/play/ ) to generate a -0 from literally typing it in source; 我无法进入游乐场( http://golang.org/doc/play/ )从字面上在源代码中输入生成-0; I'd speculate the compiler converts it to 0. 我推测编译器将其转换为0。
However, I could generate a -0 like this: 但是,我可以像这样生成一个-0:
fmt.Println(0);
fmt.Println(-0);
hmm := -1 / math.Inf(1);
fmt.Println(math.Signbit(hmm));
fmt.Println(hmm);
Prints: 打印:
0
0
true
-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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.