Box doesn't move to the position as I expect

Originally, I want to simplily move a box whose position just changes like (0,0,0)->(0,0,-1)->(0,0,-2), etc. In order to move it more realistic, I use a counter set as 50 and move the box (0,0,-0.02) and print the box’s position every time FixedUpdate() called. The psuedo-code is as follows:


function FixedUpdate () {
        if(can_move)
        {
……//other code
                }
                if(count < 50)
                {
                        Box_position += (dir/50);
Debug.Log(count+"box position now:“+Box_position.ToString("f8)));
                        count ++;
                }
                else
                 {         
                         Box_position = Box_old_position + dir;
                        
……//other code
                }
        }
}

The variant “dir” actually equals to (0,0,-1), so “dir/50” to (0,0,-0.02). The output image is as follows:


10709-unity3d_5.png


As we can see from the third to fifth figures after the decimal point in the image, it changed from “000” to “999” and then to “998”(not displayed in this image). Till now the box still move normally as I expected. However, after three times’ move(50*3 for counter variant), the box’s position suddenly changes abnormally when the counter is 42 in the fourth move like the image as follow


10710-unity3d_6.png


It suddenly changes from “998” to “001” to “007” and then to more big numbers in a “fast speed”. In addition, the x-axis coordinates also changes abnormally because the dir’s x-axis coordinates is 0.


I dont want to believe this is the Unity’s problem, so can anyone tell me why?

Floating point numbers are imprecise. They are an approximation of real numbers and suffer from rounding errors. Given the significance of the digits you highlight, there is no practical difference between the positions used and the “perfect” position for most applications. For the most part, this is not a Unity issue. This problem occurs with any application that uses floating point numbers. The only Unity issue here is that Unity elected to go with the less precise ‘float’ values rather than the more precise ‘double’ values (for valid technical reasons).

https://en.wikipedia.org/wiki/Floating_point