Re: [Algorithms] Converting floats to a specific range
Brought to you by:
vexxed72
From: Tom F. <tom...@ee...> - 2010-05-10 04:35:46
|
> x - floor(x) > > which is always nonnegative. Obscure fact - I *think* it is always non-negative, but it might not be less than 1.0. For example, if x is very small and negative, for example x=-1e-10 then floor(x) = -1.0f (correct), and then -1e-10 + 1.0f = 1.0f. It's possible you may be able to change your math rounding mode to "round down" and then it will return the smallest number less than 1.0f - I've never tried it. But yeah, frac(x) can counter-intuitively return 1.0f sometimes. TomF. > -----Original Message----- > From: Fabian Giesen [mailto:ry...@gm...] > Sent: Friday, May 07, 2010 4:56 AM > To: Game Development Algorithms > Subject: Re: [Algorithms] Converting floats to a specific range > > 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 > GDA...@li... > https://lists.sourceforge.net/lists/listinfo/gdalgorithms-list > Archives: > http://sourceforge.net/mailarchive/forum.php?forum_name=gdalgorithms- > list > No virus found in this incoming message. > Checked by AVG - www.avg.com > Version: 8.5.437 / Virus Database: 271.1.1/2838 - Release Date: > 05/06/10 18:26:00 |