Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re^3: Spaceship Zero

by graff (Chancellor)
on Nov 10, 2008 at 04:21 UTC ( [id://722548]=note: print w/replies, xml ) Need Help??


in reply to Re^2: Spaceship Zero
in thread Spaceship Zero

I think there may be some justifiable confusion between something like the "sgn()" function in BASIC, which does work just like the spaceship operator (returning -1 or 0 or 1), and something else that is more like the "copysign" function in C. There's probably a natural tendency to want to do something like this:
$delta_to_add = $magnitude * $direction; $value += $delta_to_add;
where direction is "1" for "up" and "-1" for "down"; but imagine a case where $magnitude is not zero, and $direction could be derived from or based on any value whatsoever, such that anything non-negative should count as "positive". You want to "copy" the sign bit from $direction onto $magnitude, but Perl doesn't really have a "copysign" function, and your "standard sgn()" function (like the spaceship operator) would do the wrong thing by returning zero when basis for $direction is zero, thereby setting $delta_to_add to zero as well.

I used to think there was a function that would return -1 for values less than 0, and 1 otherwise, so that you could simply use the multiplication operator to copy the sign of one variable onto another. I also dimly recall at least one discussion about this at the Monastery, but now I can't seem to locate either such a function or the previous debate. Oh well...

(updated slightly in hopes of making the 2nd paragraph clearer)

Replies are listed 'Best First'.
Re^4: Spaceship Zero (>=0)
by pKai (Priest) on Nov 10, 2008 at 08:51 UTC

    It seems obvious that >= is a different operator than <=>.

    If your want to test for something being >=0 and call it the copysign function, it's O. K., but the revelation of the OP is that spaceship zero implements the well-known Sign function abbreviated as sgn() in mathematics (not just some builtin "in BASIC".)

Re^4: Spaceship Zero
by Anonymous Monk on Nov 28, 2008 at 10:48 UTC

    Wouldn't that be:

    $x<=>0||1

    (Also; quite short)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://722548]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (8)
As of 2024-04-16 11:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found