Zero decimal: -float64 (0) from float64 (0) in Go

I want to serialize a floating point so that sign information is not lost. In particular, I would like to distinguish the negative zero of IEEE-754 from the usual zero.

language specification speaks

The result of floating point division by zero is not specified outside the IEEE-754 standard; whether panic occurs at runtime 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.

but

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

doesn't seem to work for

 n := -float64(0) 

Any ideas?

EDIT:

I registered issue 2196 to keep track of what I think is the confused difference between

 nz := -float64(0) 

and

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

as suggested by peterSO.

+4
source share
2 answers
 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 
+3
source

I could not get a playground ( http://golang.org/doc/play/ ) to create -0 by literally typing it in the source; I would suggest that the compiler will convert it to 0.

However, I could generate a -0 as follows:

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

Print

 0 0 true -0 
+3
source

Source: https://habr.com/ru/post/1369409/


All Articles