View previous topic :: View next topic |
Author |
Message |
davidb
Joined: 17 Jul 2009 Posts: 560 Location: UK
|
Posted: Thu Sep 09, 2010 7:27 pm Post subject: SIGN or ABS |
|
|
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
Code: |
SIGN_N = SIGN(1,N)
ABS_N = ABS(N)
|
Then I realised that the following was also possible.
Code: |
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] |
|
Back to top |
|
|
PaulLaidler Site Admin
Joined: 21 Feb 2005 Posts: 7925 Location: Salford, UK
|
Posted: Thu Sep 09, 2010 7:31 pm Post subject: |
|
|
It may well be done inline. i,e. directly in assembler.
Have a look at the listing produced by /explist. |
|
Back to top |
|
|
brucebowler Guest
|
Posted: Thu Sep 09, 2010 7:48 pm Post subject: Re: SIGN or ABS |
|
|
davidb wrote: | I first thought of
Code: |
SIGN_N = SIGN(1,N)
ABS_N = ABS(N)
|
Then I realised that the following was also possible.
Code: |
SIGN_N = SIGN(1,N)
ABS_N = SIGN(N,1)
|
Which is clearer?
|
To answer the "clearer" question, put your self in the shoes of the next person who has to maintain the code. the intention of the first method should be obvious to even the most casual observer (who knows a little bit about math :-). The second form is a bit more obscure.
I know if I were the next person who had to maintain the code, I'd prefer to follow someone who used the first way (or who HEAVILY documented *why* they did it the second way :-) |
|
Back to top |
|
|
JohnCampbell
Joined: 16 Feb 2006 Posts: 2554 Location: Sydney
|
Posted: Fri Sep 10, 2010 4:52 am Post subject: |
|
|
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:
Code: | 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 |
|
Back to top |
|
|
JohnHorspool
Joined: 26 Sep 2005 Posts: 270 Location: Gloucestershire UK
|
Posted: Fri Sep 10, 2010 1:07 pm Post subject: |
|
|
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:-
Code: |
if ( n .ne. 0 ) then
sign_n = n / iabs(n)
else
sign_n = 1
end if
abs _n = iabs(n) |
|
|
Back to top |
|
|
davidb
Joined: 17 Jul 2009 Posts: 560 Location: UK
|
Posted: Fri Sep 17, 2010 10:42 pm Post subject: |
|
|
Hi everyone.
In the end I settled for my first form above. |
|
Back to top |
|
|
|