I want to run a particle simulation with periodic boundary conditions - for simplicity, let's assume a 1D simulation with a region of length 1.0
. I could enforce these conditions using the following short snippet:
if (x > 1.0)
x -= 1.0;
if (x < 0.0)
x += 1.0;
but it feels "clumsy"1 - especially when generalizing this to higher dimensions. I tried doing something like
x = x % 1.0;
which takes good care of the case x > 1.0
but doesn't do what I want for x < 0.0
2. A few examples of the output of the "modulus" version and the "manual" version to show the difference:
Value: 1.896440, mod: 0.896440, manual: 0.896440
Value: -0.449115, mod: -0.449115, manual: 0.550885
Value: 1.355568, mod: 0.355568, manual: 0.355568
Value: -0.421918, mod: -0.421918, manual: 0.578082
1) For my current application, the "clumsy" way is probably good enough. But in my pursuit of becoming a better programmer, I'd still like to learn if there's a "better" (or at least better-looking...) way to do this.
2) Yes, I've read this post, so I know why it doesn't do what I want, and that it's not supposed to. My question is not about this, but rather about what to do instead.