开发者

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

开发者 https://www.devze.com 2023-03-31 03:42 出处:网络
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.

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-spec开发者_JS百科ific.

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.


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号