ᴘᴀɴᴀʏɪᴏᴛɪs ᴘᴀɴᴀʏɪᴏᴛɪs - 1 year ago 66
C Question

Efficient wrap around of doubles in C on unit axis

Consider an axis like so:


Now consider an atom placed on the axis at position:

double pos;
0.0 < pos < 1.0
. The position may be displaced by
double dt;
which can be any (+ve/-ve) double thus
double newPos = pos + dt;
could possibly not lie within the range
0.0 < newPos < 1.0

Is there any way to implement a wrap around eg. if atom leaves on the right side re-insert on the left without resulting to
(which may be too slow for my case)?

I have a feeling there should be a straight-forward way since when
is an integer (in the sense that there is no fractional part) the position remains unchanged (with wraparound) ie. adding
0.2 + 1.0
is still
) and I can extract the fractional part quickly enough using
double frac = myDouble - ((long) myDouble);
but anything I try doesn't really work on all cases.

Any ideas on this?

Answer Source

Try this:

newPos = pos + dt;
if (newPos == (long)newPos)
    newPos = 0;
else if (newPos > 0)
    newPos -= (long)newPos;
    newPos -= (long)newPos-1;

Or alternatively:

newPos = pos + dt;
newPos -= (long)newPos;
if (newPos < 0)
    newPos += 1;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download