Value wrapping

Previous topic - Next topic

MrTAToad

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) 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

spicypixel

Looks interesting is there an example you could post showing a practical use as I'm not a maths type :D
http://www.spicypixel.net | http://www.facebook.com/SpicyPixel.NET

Comps Owned - ZX.81, ZX.48K, ZX.128K+2, Vic20, C64, Atari-ST, A500.600.1200, PC, Apple Mini-Mac.

bigsofty

Very handy and an amazingly thorough article about circular values!
Cheers,

Ian.

"It is practically impossible to teach good programming style to students that have had prior exposure to BASIC.  As potential programmers, they are mentally mutilated beyond hope of regeneration."
(E. W. Dijkstra)

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
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.

MrTAToad

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.

spicypixel

Thanks TAToad. Passing CHR$ values it could be handy for a simple string encoding routine too.
http://www.spicypixel.net | http://www.facebook.com/SpicyPixel.NET

Comps Owned - ZX.81, ZX.48K, ZX.128K+2, Vic20, C64, Atari-ST, A500.600.1200, PC, Apple Mini-Mac.

Wampus

Useful little function you got there.

MrTAToad

It is indeed!