英文:
Distinguishing sign of zero : -float64(0) from float64(0) in Go
问题
我想以一种不丢失符号信息的方式对浮点数进行序列化。具体来说,我想区分IEEE-754负零和普通零。
语言规范中说
> 除以零的浮点数运算结果在IEEE-754标准之外是未指定的;是否发生运行时恐慌是与实现相关的。
这意味着我不能这样做:
n == 0 && (float64(1) / n) < 0
我尝试了math.Copysign
和math.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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论