Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Different results with the same calculation!

Discussion in 'Editor & General Support' started by nemeth-regime, May 8, 2022.

  1. nemeth-regime

    nemeth-regime

    Joined:
    Feb 13, 2017
    Posts:
    40
    This returns -11
    Code (CSharp):
    1. float f = 60f;
    2. float coeff = 0.8f;
    3. Debug.Log((int)(f * coeff - f));
    This returns -12
    Code (CSharp):
    1. Debug.Log((int)(60f * 0.8f - 60f));
    They are both the same calculation. How is it that they return different results?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,520
    I imagine that the latter example includes a constant collapse at compiler time, whereas the top one is runtime.

    I bet if you add
    const
    before
    f
    and
    coeff
    that you'd end up with the same results.
     
  3. nemeth-regime

    nemeth-regime

    Joined:
    Feb 13, 2017
    Posts:
    40
    This is correct, thanks. However this introduces another problem as the values f and coeff will be taken from arrays which can not be const as far as I understand.
     
  4. Neto_Kokku

    Neto_Kokku

    Joined:
    Feb 15, 2018
    Posts:
    1,751
    Welcome to floating point numbers! The number 0.8 cannot be represented exactly in a 32-bit float (https://float.exposed/0x3f4ccccd). The closes thing is 0.800000011920928955078, which is slightly bigger, causing the final result to be -11.9999999... instead of -12.

    The reason you get a different result when punching the numbers directly in the equation is because the C# compiler seems to use a higher precision when folding constants. When you type equations made using hard coded numbers like that, the compiler resolves them and hard coded the result in the compiled bytecode instead.