Alternate Solution to the NaN Issue?

Perhaps I was thinking too laterally here, but when challenged to prevent the NaN error, I initially thought of doing an “If” statement, then said “Nah, let’s KISS,” so I just went up to the where we defined our period and simply gave it a range

[SerializeField] [Range(.00001f, 1000f)] float period = 2f;

Which prevents it from going down to zero, but lets it go from blindingly fast to so slow you can’t really be sure it’s moving at all. And if I want to shut off the script, I just uncheck it, rather than having it running but doing nothing.

Am I being too basic here? Are there some unintended consequences of this I’m missing?

Every time I come up with one of these solutions that “does the thing” but not the way the teacher did it, I’m a bit nervous I might be breaking something down the line, as I’m such a code noob that I don’t even know what I don’t even know.

1 Like

I use two solutions to prevent NaN (which is usually caused by ‘dvide by zero’)

One: check if the number is zero before dividing, and
Two: (Sometimes) I add float.Epsilon to the divisor when I divide

float Divide(float a, float b)
{
    return a / (b + float.Epsilon);
}

I use this only in cases where I know it wouldn’t matter if the number is so very slightly off

PS: float.Epsilon is a very small number

3 Likes

wouldn’t this tiny number also move the obstcale by that much?

In this case, the numbers are being used to determine the rate of movement, but they’re used as a divisor rather than a multiplier. So, the really tiny number doesn’t matter, because any rate that’s even close to zero is going to be incredibly fast (like so fast you can’t even see it moving, just a blur). Keeping it to a minimum of epsilon just makes sure it can’t go infinitely fast.

But yeah, the flaw in the way I ‘solved’ the challenge is that there’s no way to have the obstacle not moving without either turning off or removing the script in the Unity Editor window (or putting the function in some kind of If/Else or While loop to turn it on and off using a Boolean we trigger some way or another, but that’d be a whole extra layer of complication)

@Yasser_Altamimi float.Epsilon is an extremely small number. Unity defines it as

The smallest value that a float can have different from zero.

In addition, it has a few rules (at least in the Unity engine):
Adding float.Epsilon to any number (other than zero) will just return the number, so 5f + float.Epsilon = 5f. The same goes for subtraction.
Adding or subtracting float.Epsilon to/from zero will return float.Epsilon (or -float.Epsilon when subtracted)

It is too small to make any noticeable difference to anything

1 Like

Thanks to you in the thread. I found the extra explanation of Epsilon interesting and helpful. It seems to me a better approach to just add Epsilon to the value in this situation than check it and not move the object if it seems to be zero.

1 Like

Privacy & Terms