My attempt to get back into coding after a long break is not going well. I just want this platform to move between two points-- it’s not that complicated, and I’ve done something like it before.
I know this can’t be true, but it seems like the computer is failing at basic arithmetic. I’m getting a weird result when I compare the y-position of the platform and its target waypoint. Both have the y-position value -2.9.
Debug.Log("target y pos: " + wayPoints[targetWaypoint].transform.position.y + ", platform y pos: " + transform.position.y);
Debug.Log("y diff:" + (wayPoints[targetWaypoint].transform.position.y - transform.position.y));
The top debug gives me -2.9 and -2.9, as expected. The bottom, however, is giving me 2.3841… when it should be 0.
This must be a situation where I’m missing something that will make me facepalm once it’s apparent. Please help me feel like a doofus for whatever dumb mistake is invisible to me at the moment so that I can move on.
I suspect I know what’s happening - can you copy/paste and/or screenshot the actual resulting value, not just retype it?
I bet a dollar that you’re only looking at the beginning of the number, and in full it looks something like 2.3841320651561E-15. Assuming that’s correct, this is just floating point imprecision combined with scientific notation. The E at the end is a shorthand for “times 10 to the Nth power”, and if there’s a large negative number after it, then the actual number is something like 0.0000000000000002384. That tiny value would be a result of floating point imprecision and is effectively zero. Floating point imprecision is a fact of life for CPUs and you have to learn to work around it. In general this just means that you never use == on two floats (or float=based data types).
Look more closely on the ‘…’ of the number. if there’s a hyphen (minus sign) somewhere in there, it’s a negative exponent, and you have a number reaaaaaaaly close to zero, just not exactly zero because you are dealing with floating point arithmetic.
Thank you both. I’m aware of floating point precision errors, but apparently I wasn’t recognizing the full extent of how they can screw things up for two reasons:
The output for these values was showing a plain value, unambiguously 2.9.
I did indeed overlook the ‘-’ by the “E” and I had forgotten what a negative exponent means. Because the calculated difference was showing 2.x rather than 0.x, I figured that was much too big a number to account for floating point error.
That’s just an artifact of whatever formatting the implicit .ToString() method sent it through.
Unity provides a Mathf.Approximately() method for float comparisons, but personally I like to make my own that simply compares to an Epsilon (error band) that I control directly, rather than the implicit one from Unity.
Good to know! I only just today learned about Mathf.Epsilon, which is nuts since I spent around 3 years making my first game, and it would have been useful in numerous places.