Search Unity

Weird behavior of a simple mod operation. (Wrong result)

Discussion in 'Scripting' started by AdamLiu, Nov 9, 2014.

  1. AdamLiu

    AdamLiu

    Joined:
    Mar 19, 2014
    Posts:
    71
    Hey guys, I have a script here:

    Code (CSharp):
    1. float s = 1f / 3;
    2. Debug.Log( (1%s).ToString());
    Obviously, the correct answer should be a very very small float close to 1, but the output in Unity is this:

    0.3333333
    UnityEngine.Debug:Log(Object)

    This is obviously an wrong answer.
    However, if you use
    Code (CSharp):
    1. float s = 0.333333f
    ,
    then the answer is correct.

    Can anyone tell me why is this happening?
     
    Last edited: Nov 10, 2014
  2. GarthSmith

    GarthSmith

    Joined:
    Apr 26, 2012
    Posts:
    1,240
    The string representation of a float is normally rounded. To get near-full precision, you can use the "G9" string formatter in your debug messages.
    Code (csharp):
    1. float third = 1f / 3;
    2. float threes = 0.333333f;
    3.  
    4. Debug.Log("third's representation: " + third.ToString("G9"));
    5. Debug.Log("threes's representation: " + threes.ToString("G9"));
    The output:
    third's representation: 0.333333343
    three's representation: 0.333332986

    You should notice that 1f/3 is actually just slightly ABOVE a true mathematical one-third. Meanwhile, 0.333333f's true value is slightly BELOW one-third. Knowing this, the differences in modulo operation makes sense.

    Computer's track numbers in binary while we think in decimal. Most decimal numbers CANNOT be perfectly represented in binary, so floats will almost always have close but not exact values. This is also why we usually don't directly compare two floats for equality, but instead make sure they're just really close to each other.
     
    Last edited: Nov 24, 2014
    AdamLiu likes this.
  3. AdamLiu

    AdamLiu

    Joined:
    Mar 19, 2014
    Posts:
    71
    I really appreciate that you gave such a clear and informative answer. Thumb up for you and the Unity community. Thank you very much, sir.
     
    GarthSmith likes this.