ᴘᴀɴᴀʏɪᴏᴛɪs - 4 months ago 23

C Question

Consider an axis like so:

Now consider an atom placed on the axis at position:

`double pos;`

`0.0 < pos < 1.0`

`double dt;`

`double newPos = pos + dt;`

`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

`fmod`

I have a feeling there should be a straight-forward way since when

`dt`

`0.2 + 1.0`

`0.2`

`2.0,3.0...`

`double frac = myDouble - ((long) myDouble);`

Any ideas on this?

Answer

Try this:

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

Or alternatively:

```
newPos = pos + dt;
newPos -= (long)newPos;
if (newPos < 0)
newPos += 1;
```