Avoiding NaN by using frequencies instead of periods

Just wanted to share my approach to avoiding division by zero. An interpretation that is wrong, is that “if we put 0, we expect nothing to happen”; au contraire, with a period of 0, we’re actually saying that we want to move back and forth within 0 seconds, or infinitely fast! No rocket science here, that’s just a different interpretation of that error: we indeed get an error, because we’re asking that obstacle to move infinitely fast!!

So, looking at the problem this way, a solution would be to define a min period that makes sense (e.g., I don’t want the user to set a period lower than 1ms). In fact, that’s indeed what Rick is doing, we’re not allowing any period smaller than Mathf.Epsilon (so, we’re still allowing extremely fast oscillations).

I did it differently, without needing to check anything. Basically, instead of working with periods, I’m working with frequencies (by definition the inverse of the period). This avoids division altogether because we now have float cycles = Time.time * frequency;. Now, a value of 0 is indeed “do nothing”, a value of 0.1 means “do almost nothing” (10% of a cycle each second), a value of 1 will oscillate slowly, a value of 10 will oscillate much faster. Even without the NaN issue, I personally prefer frequencies because “higher values” now mean “faster oscillations”

6 Likes

Good Idea

I like this solution/method, thanks for posting it!

1 Like

Privacy & Terms