Silverfrost Forums

Welcome to our forums

SIGN or ABS

9 Sep 2010 6:27 #6927

I have some code where I need to extract the sign of an integer and its absolute value (so for -12, I need the sign -1 and the number 12.)

There are many ways to do this, but which is best. In my application I don't need to worry about 0 which has a sign of +1 (usually!).

I first thought of

SIGN_N = SIGN(1,N)
ABS_N  = ABS(N)

Then I realised that the following was also possible.

SIGN_N = SIGN(1,N)
ABS_N  = SIGN(N,1)

Which is clearer? Is ABS() really just a special kind of SIGN(). How is it implemented in the compiler?

[/code]

9 Sep 2010 6:31 #6928

It may well be done inline. i,e. directly in assembler.

Have a look at the listing produced by /explist.

10 Sep 2010 3:52 #6929

I know the second version would send me to the fortran documentation, as I always forget the order required in SIGN. An alternative could be:

   if (n < 0) then
     sign_n = -1
     abs_n = -n
   else
     sign_n = 1
     abs_n = n
   end if

There is no ambiguity with this example, including if n=0 John

10 Sep 2010 12:07 #6930

John,

I don't understand your post, because David requires the absolute value to be positive '(so for -12, I need the sign -1 and the number 12.)'

why not do:-

    if ( n .ne. 0 ) then
        sign_n = n / iabs(n)
    else
        sign_n = 1
    end if

  abs _n = iabs(n)
17 Sep 2010 9:42 #6961

Hi everyone.

In the end I settled for my first form above.

Please login to reply.