IEEE754 supports the negative zero. But this code
a := -0.0
fmt.Println(a, 1/a)
outputs
0 +Inf
where I would have expected
-0 -Inf
Other languages whose float format is based on IEEE754 let you create negative zero literals
Java :
float a = -0f;
System.out.printf("%f %f", a, 1/a); // outputs "-0,000000 -Infinity"
C# :
var a = -0d;
Console.WriteLine(1/a); // outputs "-Infinity"
Javascript :
var a = -0;
console.log(a, 1/a); // logs "0 -Infinity"
But I couldn't find the equivalent in Go.
How do you write a negative zero literal in go ?
There is a registered issue.
And it happens to give a kind of solution :
a := math.Copysign(0, -1)
It's not so bad as it obviously refers to the standard copysign
function defined by IEEE754
.
But this means you need to import a package and this still looks much too heavy for the (admittedly minor and rare) need.
package main
import (
"fmt"
"math"
)
func main() {
a := 1. / math.Inf(-1)
fmt.Println(a, 1/a)
}
(Also here)
Output:
-0 -Inf
I just tried out this and it seems to work for me .
package main
import (
"fmt"
)
func main() {
zero := float64(0)
neg_zero := -zero
fmt.Println(zero, neg_zero)
}
Though it does not work as expected when I do neg_zer0 := - float64(0)
来源:https://stackoverflow.com/questions/13804255/negative-zero-literal-in-golang