Re: Converting floats to a specific range

Fabian Giesen <[email protected]> Fri, 07 May 2010 13:56:25 +0200
Newsgroups gmane.games.devel.algorithms
Message-ID <[email protected]>
On 07.05.2010 13:36, Zafar Qamar wrote:
> Hi,
>
> I'm sure this problem is pretty simple, but here goes...
>
> I have a set of float numbers that I'm trying to auto-wrap within a specific range of 0.0 to wrapSize (wrapSize is positive, and not a power of 2)
>
> So, if I choose a wrapSize of 1.0 then I want the following to happen when I feed in numbers...
 > [..]

There's a standard C library function, fmod, that nearly does what you 
want. The one thing you need to fix is that fmod(x, wrapSize) is 
negative whenever x is. So the solution to your problem is

   fmod(x, wrapSize) + (x < 0.0 ? wrapSize : 0.0);

The special case for wrapSize == 1 is quite easy, and worth remembering, 
since you get to avoid the conditional: You can just compute

   x - floor(x)

which is always nonnegative.

If your target platform/language doesn't have fmod but does have floor, 
you can usually make do with

   x - wrapSize * floor(x / wrapSize)

but if you use this you need to watch out if you might encounter very 
large values of x in your application - as soon as floor(x / wrapSize) 
gets to the range where neighboring floats are more than 1 apart, this 
expression will break.

-Fabian

------------------------------------------------------------------------------

_______________________________________________
GDAlgorithms-list mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/gdalgorithms-list
Archives:
http://sourceforge.net/mailarchive/forum.php?forum_name=gdalgorithms-list