[Gambas-user] function to "wrap" a number between upper and lower bounds
Tobias Boege
taboege at ...626...
Thu Dec 13 14:19:02 CET 2012
On Wed, 12 Dec 2012, Kevin Fishburne wrote:
> On 12/12/2012 05:33 PM, Kevin Fishburne wrote:
> > I need a function like:
> >
> > Wrap(number, lowerbound, upperbound)
> >
> > such that Wrap(5,1, 3) will return 2. In other words, it "wraps" the
> > number around the supplied bounds and returns where it "lands". I
> > believe it would work similarly to assigning a value to a datatype
> > outside its scope, like assigning 300 to a Byte type.
> >
> > I looked up some solutions online and none of them really seemed to work
> > properly and their comments were surrounded by debate. Is there an
> > efficient way to do this, and does anyone think it would be a useful
> > function to add to Gambas itself?
> >
>
> I found this:
>
> |int Wrap(int kX, int const kLowerBound, int const kUpperBound)
> {
> int range_size= kUpperBound- kLowerBound+ 1;
>
> if (kX< kLowerBound)
> kX+= range_size* ((kLowerBound- kX) / range_size+ 1);
>
> return kLowerBound+ (kX- kLowerBound) % range_size;
> }|
>
>
> however it relies on the Mod operator (%), which I think means it will
> only work for integers. Is there a way to do this for singles/floats?
>
Maybe the best thing you can do is to use the C math library function fmod()
which does modulo for Float. Then use Benoits algorithm. fmod() - I'm almost
certain - knows how to optimise the calculations, e.g. if your FPU has
support for that operation, etc.
If you look at the manpage, have in mind that Gambas' "Float" is C's
"double" and Gambas' "Single" is C's "float".
Regards,
Tobi
More information about the User
mailing list