Go: to inifinity and beyond

When I read and review code, I sometimes come across constructions which seem strange, dubious or generally weird. Before I comment, I like to check my assumptions and understanding of the behaviour first. Go makes this really simples with Playground where you can run short snippets of code and share them with colleagues.

Yesterday, I came across a conditional with division which just asked to get zero divisor. I assumed the code would fail but it was strange it hasn’t manifested, so I went to check. I took the code:

if (math.Abs(someValue) / anotherValue) > someThreshold {
	// do stuff
}

and boiled it down to:

if (math.Abs(5.0)/0.0 > 1) {
    fmt.Println("greater than one")
}

This code compiles, runs and prints the string. OK, so what is the result of division by zero?

fmt.Println(math.Abs(5.0)/0.0)
// +Inf

Alright, that sort of makes sense and complies with the Go language spec:

For floating-point and complex numbers, +x is the same as x, while -x is the negation of x. The result of a floating-point or complex division by zero is not specified beyond the IEEE-754 standard; whether a run-time panic occurs is implementation-specific.

The type of the infinity is:

fmt.Printf("%T", math.Abs(5.0)/0.0) // float64

Sure, it’s float64 division, so it should yield float64 value as well, but the same spec says that there are no infinity constants:

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.

To muddy the water bit more

if (5.0/0.0 > 1) {
    fmt.Println("greater than one")
}

doesn’t compile but

foo := 0.0
if (5.0/foo > 1) {
    fmt.Println("greater than one")
}

does. I didn’t try to dig deeper, but I assume the last two cases are a result of a compile time check which is looking for division of an int or float by zero literal. For some reason, it is ok with a function call divided by zero.

There’s no big takeaway, it’s just an unusual corner of floating point arithmetic.

We're looking for developers to help us save energy

If you're interested in what we do and you would like to help us save energy, drop us a line at jobs@enectiva.cz.

comments powered by Disqus