## Jerk jumping assignments are bad

Do you deal with incrementing values of a cyclic nature? For example, angular values used in sine functions? Then be careful when you reach the cycle’s end.

Back when I was doing an OpenGL class project in university, there was this Ferris wheel simulation. The Ferris wheel was going to keep turning, and there’s a variable keeping track of the angle of rotation.

Even though a `float`

or `double`

can take in large values, there’s still the possibility that it would overflow if unchecked. So most of us (the students) just keep the variable to within the [0, 2*PI) range.

The thing was, some students jerk jump the assignment as follows:

if (rot > 2*PI) { rot = 0.0; }

Well, there’s nothing wrong with getting it back to square zero, isn’t it?

Ahh, but PI is an irrational number, and couple that with the sometimes inexact representation of floating point variables, it means the variable `rot`

is probably *never* exactly 2*PI. This means (rot – 2*PI) is greater than zero. And the students just smashed that difference to pieces.

It also meant their Ferris wheels would appear jerky. The Ferris wheels would rotate until 2*PI was exceeded, and then snap back to when they’re at zero rotation. Depending on how much their increments were (which affected the speed of rotation), the jerky movements could be more pronounced.

The smoother solution is to subtract a full cycle value:

if (rot > 2*PI) { rot -= 2*PI; }

There’s a caveat. It assumes the incremental value is less than 2*PI. That’s a safe assumption. It’s not like you’d do something like this, right?

rot += (2*PI + 0.5); if (rot > 2*PI) { rot -= 2*PI; }

Right?!?!

This reminds me of sinks and diverging values in chaos theory… f(x)=x^2 tends to zero if x<1, but goes to infinity if x>1.

Anyway, be careful of assignments when you reach boundaries. Because jerk jumping assignments are bad.