Sgn value
Parameters
| value - any integer or float expression |
Description
|
Returns -1, 0 or 1 depending on whether the value is negative, zero or positive. Sgn is a prefix operator like Abs, so Sgn x and Sgn(x) are the same thing. Bracket anything longer than a single variable. The result carries the type of the input. Sgn(-9) gives the integer -1, while Sgn(-2.5) gives the float -1.0. If you are printing it and want a plain "-1" rather than "-1.0", store it in an integer variable first. Think of Sgn as "which way", stripped of "how far". It turns a difference into a direction: step = Sgn( target_x-x ) moves a chaser one tile per frame towards its goal, whichever side it started on, and stops of its own accord when the two line up and Sgn returns 0. Multiplying by Sgn also lets you apply something like friction or recoil in the correct direction without writing an If for each case. See also: Abs, Int, Floor, Ceil. |
Example
; Sgn Example ; ----------- ; Sgn reports only the sign of a number: ; 1 for positive, -1 for negative, 0 for zero. Print "Sgn(10) = "+Sgn(10) Print "Sgn(-10) = "+Sgn(-10) Print "Sgn(0) = "+Sgn(0) Print "Sgn(5.5) = "+Sgn(5.5)+" (a float in gives a float back)" Print "Sgn(-5.5) = "+Sgn(-5.5) Print "" ; Handy for movement: which way should an enemy walk to reach the ; player? Sgn turns any distance into a simple -1, 0 or 1 direction. enemy=340 player=100 Print "Enemy at x="+enemy+", player at x="+player Print "Walk direction: Sgn(player-enemy) = "+Sgn(player-enemy) Print "(1 means walk right, -1 walk left, 0 already there)" Print "" Print "Press any key to close the example" WaitKey End
Index