math.Abs vs if value < 0

146 views
Skip to first unread message

Diego Augusto Molina

unread,
Oct 19, 2024, 10:28:58 AM10/19/24
to golang-nuts
Hi! I wanted to ask what is the difference between the current implementation of math.Abs and the following:

```go
func Abs(x float64) float64 {
    if x < 0 {
       return -x
    }
   return x
}
```

math.Abs would appear to return a copy of the input with the sign bit set to zero. I tried the special conditions of NaN (the one returned by math.NaN()), +Inf, and -Inf and the above would appear to work the same.

I guess my main question is: would "-x" behave differently under any condition? Was there a particular motivation for the current implementation? Not judging nor asking for any change, just trying to learn.

Thank you!

Axel Wagner

unread,
Oct 19, 2024, 2:42:50 PM10/19/24
to Diego Augusto Molina, golang-nuts
It gives a different result for -0: https://go.dev/play/p/LAVIaAZsVNi
Also, the math.Abs implementation is branch-less. Depending on what the compiler makes of either, that might perform better.

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/0cffdc6f-65c3-45c1-b003-ef3c27a0542en%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages