区分零的符号:Go 中的 -float64(0) 与 float64(0)
我想以不丢失符号信息的方式序列化浮点。具体来说,我想区分 IEEE-754 负零和常规零。
语言规范说
浮点除以零的结果未在 IEEE-754 标准之外指定;是否发生运行时恐慌是特定于实现的。
这表明我不能这样做
n == 0 && (float64(1) / n) < 0
,我尝试了 math.Copysign
和 math.Signbit
上面写着
如果 x 为负数或负零,func Signbit(x float64) bool
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
returnstrue
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
输出:
Output:
我无法访问 go Playground ( http://golang.org/doc/play/ )从源代码中逐字输入生成 -0;我推测编译器会将其转换为 0。
但是,我可以生成这样的 -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:
Prints: