Groups keyboard shortcuts have been updated
Dismiss
See shortcuts

Absolute value of integers

7,584 views
Skip to first unread message

JONNALAGADDA Srinivas

unread,
Jul 21, 2010, 2:37:18 PM7/21/10
to golang-nuts
Package `math' does not seem to provide `Iabs()' corresponding
to the function `Fabs()'. Is there any particular reason? Thanks.

Greetings,
JS

ptolomy23

unread,
Jul 21, 2010, 2:53:09 PM7/21/10
to JONNALAGADDA Srinivas, golang-nuts
Probably because just doing
if n < 0 {
   n = -n
}
is not error prone or particularly worth an import.

The "math" package seems to operate pretty much entirely on float64, and has
specialized assembly implementations to ensure that these operations are efficient. For floats, you have the -0 case, which people tend to forget about, so the function saves us from that.
Without generics, we'd have to pick between int, int64, and int32 for the type of Iabs() or possibly have three different functions. These functions would be out of place in "math", and would be less efficient than the "if" way, all for a savings of ~2 lines. So, I would guess Iabs isn't provided because people haven't found a real need, and it would be rather awkward if it did exist.

Cory Mainwaring

unread,
Jul 21, 2010, 3:00:16 PM7/21/10
to ptolomy23, JONNALAGADDA Srinivas, golang-nuts
The entire math library is based on float64. Are all of the functions of the math library as easy to reproduce in integers as Abs?

Russ Cox

unread,
Jul 21, 2010, 3:11:38 PM7/21/10
to Cory Mainwaring, golang-nuts
On Wed, Jul 21, 2010 at 12:00, Cory Mainwaring <olr...@gmail.com> wrote:
> The entire math library is based on float64. Are all of the functions of the
> math library as easy to reproduce in integers as Abs?

Ceil, Floor, and Trunc are even easier!

Russ

Cory Mainwaring

unread,
Jul 21, 2010, 3:14:47 PM7/21/10
to r...@golang.org, golang-nuts
I was talking more like Pow and such. Would it be a bad idea to implement some Integer versions of those functions in the math library?

JONNALAGADDA Srinivas

unread,
Jul 21, 2010, 4:07:55 PM7/21/10
to golang-nuts
<< The "math" package seems to operate pretty much entirely on
float64, ... . For floats, you have the -0 case, which people tend to
forget about, so the function saves us from that. >>

Agreed.

<< Without generics, we'd have to pick between int, int64, and int32
for the type of Iabs() or possibly have three different functions. >>

Not really, since as you mentioned above, `math' operates
pretty much entirely on `float64'. Similarly, for integer operations,
only int64 versions could have been provided. That was just for
argument :-)
In any case, looking at `java.lang.Math', for a comparison, we
notice only three functions for integers, viz. `abs', `max' and `min',
but they are there. I probably was expecting analogously!

Greetings,
JS
Reply all
Reply to author
Forward
0 new messages