Codesnippets > Math

Value wrapping

(1/2) > >>

I think I've finally found a routine that can correctly wrap values around postive and negative numbers, based on this code : http://www.codeproject.com/KB/recipes/Circular-Values.aspx

--- Code: (glbasic) ---FUNCTION wrap:value,minRange,maxRange
LOCAL diff

diff=maxRange-minRange
IF value>=minRange
IF value<maxRange
RETURN value
ELSE
IF value<maxRange+diff
RETURN value-diff
ENDIF
ENDIF
ELSE
IF value>=minRange-diff
RETURN value+diff
ENDIF
ENDIF

RETURN MOD(value-minRange,diff)+minRange
ENDFUNCTION
--- End code ---

spicypixel:
Looks interesting is there an example you could post showing a practical use as I'm not a maths type :D

bigsofty:
Very handy and an amazingly thorough article about circular values!

Ruidesco:

--- Quote from: spicypixel on 2011-Oct-15 ---Looks interesting is there an example you could post showing a practical use as I'm not a maths type :D

--- End quote ---
Very simple example: imagine for example that you have a 3D game with "tank" controls a la Resident Evil. All of the angles you can rotate to are between 0 and 359; sure, you can rotate to 360 (and further, or below zero angles) but that is the same as rotating to 0.

--- Quote from: spicypixel on 2011-Oct-15 ---Looks interesting is there an example you could post showing a practical use as I'm not a maths type :D

--- End quote ---
Easiest way of using it is :

--- Code: (glbasic) ---value=wrap(org,-5.0,10.0)

--- End code ---
Any value outside the -5 to 10.0 range will be wrapped around, so -6 becomes 9, and 11.0 because -4, 12 because -3 and so on...

As Ruidesco as stated, the most frequest use will be to make sure a value is always between 0 and 359, no matter how much outside these ranges it is.