Re: abs()

new topic     » goto parent     » topic index » view thread      » older message » newer message

Chris Bensler wrote:
> FD(censored) wrote:
> 
>>hey i remember ages ago someone posted asking the quickest way to code 
>>an abs() function. The results were good, but a few who posted at the 
>>end of the thread posted very very efficient ways to do this in 
>>euphoria, which i cannot remember. I'm looking for speed here. Any help 
>>would be appreciated
> 
> I dunno about the fastest, but this beats most attempts..
> 
> }}}
<eucode>
> global function abs(object x)
>   if atom(x) then
>     if x < 0 then return -x else return x end if
>   else
>     for i = 1 to length(x) do
>       if x[i] < 0 then x[i] = -x[i] end if
>     end for
>   end if
>   return x
> end function
> </eucode>
{{{


There's fast code and there's fast (easy) to type. The above function is 
close to the fast code solution, but fails on sequences of sequences...

This minor change solves that:

global function abs(object x)
   if atom(x) then
     if x < 0 then return -x else return x end if
   else
     for i = 1 to length(x) do
       x[i] = abs(x[i])
     end for
   end if
   return x
end function


The easy to type version (but not guaranteed to be fast) is:

global function abs(object x)
     return x*((x>0)-(x<0))
end function


> if you don't have to deal with sequences (which you likely do not), you 
> can optimize for atoms..
> 
> }}}
<eucode>
> global function abs(atom a)
>   if a < 0 then return -a else return a end if
> end function
> </eucode>
{{{


Carl

-- 
[ Carl R White == aka () = The Domain of Cyrek = ]
[ Cyrek the Illogical /\ www.cyreksoft.yorks.com ]

new topic     » goto parent     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu