in reply to Re^2: Very basic question on performance
in thread Very basic question on performance

Or more accurately:

sub ediag { return abs($_[0]) * abs($_[1]); }

...or...

sub ediag { abs(shift) * abs(shift); }

It's possible (maybe even probable) that since the OP showed one subroutine that did this:

sub one { sqrt( $_[0] * $_[0] * $_[1] * $_[1] ) }

...and another that did this:

sub another{ sqrt( $_[0] * $_[0] + $_[1] * $_[1] ) }

...that we (I) should have been looking at his second example all along, and should have considered the first one a typo. If that's the case, then the square root of the sum of two squares does make more sense.


Dave

Replies are listed 'Best First'.
Re^4: Very basic question on performance
by morrin (Acolyte) on Mar 14, 2014 at 15:28 UTC
    Thanks Dave, you were correct. I had a typo. It was suppose to be the square root of the sum of the squares for both. :-)
Re^4: Very basic question on performance
by Laurent_R (Canon) on Mar 14, 2014 at 18:42 UTC
    Yes, Dave, you are correct, it should rather be something like:
    return abs ( $_[0] * $_[1]);
    But my point was really to say that, although I am very often using named variables for better clarity (and also to avoid changing inadvertently the parameter in the calling function), I found that, in this case, the ediag function is in my humble opinion actually clearer than the vdiag function, because you can see immediately the math expression being returned to the caller.

      Yes, I'll agree. With that in mind, and given another followup from the OP, it seems that what he really wants is this:

      sub diag { sqrt( $_[0]^^2 + $_[1]^^2 ); }

      ...or possibly...

      sub diag { sqrt( shift^^2 + shift^^2 ); # Not sure if this is more readable, or + not. }

      Or if he's in a really tight loop where every cycle counts, possibly an Inline::C version of the same.


      Dave

        Yes, I agree and had noted the OP's new message. In fact, I would consider this:
        sub diag { my ($x, $y) = @_; sqrt( $x^^2 + $y^^2 ); }
        to still be very fine (perhaps slightly slower, but very clear), but the way the original script was coded with numerous intermediate variables (to store the squares, etc.) actually made the things more complicated to follow than a single and simple math expression which all of us presumably can understand at first glance.