Search code examples
godivide-by-zero

go float zero division compiler error


How does this behaviour sense? wouln't it make mor sense to just print an compiler warning instead of an error?

func main() {
var y float64 = 0.0
var x float64 = 4.0 / y
fmt.Println(x)
}

+Inf

func main() {
var x float64 = 4.0 / 0.0
fmt.Println(x)
}

prog.go:9:22: division by zero


Solution

  • Golang numeric consts are special. They're not directly mapped to any IEEE754 float type, and they're not able to store infinities or -0 for example.

    From the documentation:

    Numeric constants represent exact values of arbitrary precision and do not overflow. Consequently, there are no constants denoting the IEEE-754 negative zero, infinity, and not-a-number values.

    This choice brings some power, as it reduces overflowing in constants:

    var x float64 = 1e1000 / 1e999 // yes, this is 10
    

    If you need an infinity value you may do

    var x float64 = math.Inf(1)