Sin function returns NaN
I'm trying to figure out why this function is returning a NaN value for v3.y. The object of the script is to move the "centerPoint" up and down using the sin. Whenever the script runs from the beginning of the scene this code throws a NaN error. However if I enable the script after the scene is run it works without throwing an error. I'm guessing it may be because centerPoint starts at 0, but I am not sure. Seeking guidance and help!
Vector3 v3 = centerObject.localPosition;
v3.y = Mathf.Sin(Time.time * _frequency + phase + (centerPoint / width)) * amplitude;
centerObject.localPosition = v3;
To sum up the answer below -- the problem has nothing to do with the sin function. The problem is the math before it. The input was NaN (which is a special float value meaning Not A Number) so sin gave you NaN right back.
If you redid it as val=Time.time + _frequency + phase + (centerPoint / width); then you'd see val is NaN.
Right, though the argument could also be +-infinity which would also result in a NaN result for the Sin function. A division by zero (for floating point numbers) in almost all cases will return one of the infinities. Only the special case of 0/0 will result in NaN. Even this works: inf/0. It's also just infinity. Of course a sign flip is possible since the IEEE floating point format supports a signed zero. Without a signed zero infinity wouldn't make sense. That's where the floating point format actually differs from the formal mathematics definition. I'm not sure why wikipedia does not list sin and cos in the operations that produce NaN. There are other trigonometric functions that will return proper values when infinity is passed like aTan(infinity) which returns PI/2 (aka 90°)
Sure, there are details. $$anonymous$$y point is that for starting out, and 99% otherwise, the only thing to know is how 3-letter words ins$$anonymous$$d of numbers means "math error". Check the formula, probably for division by 0.
I don't want the OP to feel they need to look up negative-INF, and so on.
Answer by unity_ek98vnTRplGj8Q · Jan 08, 2020 at 04:01 PM
Often NaN's happen when you divide by 0. Make sure your width is set before the first time the function executes (try adding a Debug.Log(width) right before your code)
Dividing by zero does almost never result in NaN but in positive or negative infinity. Only 0/0 results in NaN. However you are right that this is probably the cause. Because sin(infinity) will also result in NaN.
Good to know, thanks for the correction!
Your answer
Follow this Question
Related Questions
A graph to render sine wave with custom resolution 0 Answers
Error with String in code 1 Answer
How can I numerically solve an equation in Unity c#? 2 Answers
unexpected void error 1 Answer