GLBasic forum

Codesnippets => Math => Topic started by: MrTAToad on 2011-Oct-15

Title: Value wrapping
Post by: MrTAToad on 2011-Oct-15
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 (http://www.codeproject.com/KB/recipes/Circular-Values.aspx)

Code (glbasic) Select
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
Title: Re: Value wrapping
Post by: 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
Title: Re: Value wrapping
Post by: bigsofty on 2011-Oct-15
Very handy and an amazingly thorough article about circular values!
Title: Re: Value wrapping
Post by: Ruidesco on 2011-Oct-15
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
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.
Title: Re: Value wrapping
Post by: MrTAToad on 2011-Oct-15
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
Easiest way of using it is :

Code (glbasic) Select

value=wrap(org,-5.0,10.0)

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.
Title: Re: Value wrapping
Post by: spicypixel on 2011-Oct-15
Thanks TAToad. Passing CHR$ values it could be handy for a simple string encoding routine too.
Title: Re: Value wrapping
Post by: Wampus on 2011-Oct-16
Useful little function you got there.
Title: Re: Value wrapping
Post by: MrTAToad on 2011-Oct-17
It is indeed!