We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
Page Index Toggle Pages: 1
wrap number (Read 696 times)
wrap number
Mar 18th, 2010, 4:05am
 
Hi,

How do I wrap a number between values, so that if the number exceeds the high value it would start at my provided low value? Similar to constrain()... something like this:

wrap(value, high, low)

wrap(10, 0, 8) //this will wrap the number 10 down to 1
wrap(20, 26, 40) //this will wrap the number 20 up to 31

cheers,
g
Re: wrap number
Reply #1 - Mar 18th, 2010, 4:26am
 


you would have to do :

if (number > valueMax) {number = valueMin;}
else if (number < valueMin) {number = valueMax}

Wink
Re: wrap number
Reply #2 - Mar 18th, 2010, 4:36am
 
Im new to processing, but there should really be a function like this no?:

int wrap(int v, int minv, int maxv )
{
   while(v > maxv) {
   v= -maxv;}
   while(v < minv) {
   v= v+(abs(minv));}
   return v;
}

..or do you usually all users make all these basic functions themselves?

cheers, g

ps
@Chrisir:
your code will clip the value - if the number was 5 above my max value it would just clip down to my min value...
Re: wrap number
Reply #3 - Mar 18th, 2010, 4:40am
 
you better use modulo to do that
http://processing.org/reference/modulo.html
Re: wrap number
Reply #4 - Mar 18th, 2010, 5:19am
 
value = low + value % (high - low + 1);
Re: wrap number
Reply #5 - Mar 18th, 2010, 7:45am
 
PhiLho  wrote on Mar 18th, 2010, 5:19am:
value = low + value % (high - low + 1);


nicely and concisely expressed :)
...tho except when 'value' is negative, since java's % is a remainder operator not a true modulo as used in "modular arithmetic".  fe try wrapping -15 into 0,10 --> -4, just something to be aware of.
Page Index Toggle Pages: 1