9

I was playing around with Go, and found this particular interesting code for the abs function in the math package:

http://golang.org/src/pkg/math/abs.go

14 func abs(x float64) float64 {
15      switch {
16      case x < 0:
17          return -x
18      case x == 0:
19          return 0 // return correctly abs(-0)
20      }
21      return x
22  }

Why do we need to have the special case of x == 0? What will happen if I delete line 18 and 19?

user84386
  • 107

3 Answers3

18

The comment explains the reason - abs(-0) should return 0, but without the special case, abs(-0) would return -0.

I assume Go uses IEEE floats so both +0 and -0 can be represented using different values for the sign bit.

Lee
  • 927
10

The IEEE 754 floating-point standard allows signed zeros. A negative zero is equal to a positive zero, so it wouldn't be covered by the < 0 test.

parsifal
  • 483
  • To colour in some rationale: It's a useful feature in numerical analysis, that let's you discern a function that converges to 0 from the left, from one that converges to 0 from the right. – Alexander Mar 22 '22 at 20:39
0

-0 and +0 are represented in memory with the same bit patterns as if in the CPU or a register. +0 is 0x0000 0000 in 32-bit IEEE floating point. -0 is 0x8000 0000 The difference is the sign bit. The same representations everywhere. They represent the SAME real number, namely zero. There is no sign for zero in the real number system.

Absolute value is evidently defined by the IEEE standard to require that the sign bit of the result is always 0. Hence the special case in the code.

Rob
  • 1