Search Unity

  1. We are migrating the Unity Forums to Unity Discussions. On July 12, the Unity Forums will become read-only. On July 15, Unity Discussions will become read-only until July 18, when the new design and the migrated forum contents will go live. Read our full announcement for more information and let us know if you have any questions.

Question Debug.Log(2000.0f * 000.1f); is 200

Discussion in 'Editor & General Support' started by twobob, Aug 8, 2021.

  1. twobob

    twobob

    Joined:
    Jun 28, 2014
    Posts:
    2,058
    Debug.Log(2000.0f * 000.1f);

    Someone help me out here.
    Why is that.
     
  2. grizzly

    grizzly

    Joined:
    Dec 5, 2012
    Posts:
    357
    0.1 is 10%. What were you expecting?
     
    Joe-Censored, _geo__ and twobob like this.
  3. twobob

    twobob

    Joined:
    Jun 28, 2014
    Posts:
    2,058
    lol yeah. sorry I misread/missed the misplaced decimal point: XD more coffee required
     
    Joe-Censored and grizzly like this.
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    39,571
    Now that you have had your coffee, don't forget about floating point imprecision:

    Code (csharp):
    1. // @kurtdekker: don't forget about floating point imprecision
    2. using UnityEngine;
    3. public class FloatingPointImprecision : MonoBehaviour
    4. {
    5.     void Start ()
    6.     {
    7.         float a = 2000.0f;
    8.         float b = 0.1f;
    9.         float product = (a * b);
    10.         float answer = 200;
    11.  
    12.         Debug.Log( "a = " + a);
    13.         Debug.Log( "b = " + b);
    14.         Debug.Log( "product of a*b = " + product);
    15.         Debug.Log( "answer = " + answer);
    16.         Debug.Log( "does product equal answer? " + (product == answer));
    17.         Debug.Log( "does a*b equal answer? " + ((a * b) == answer));
    18.     }
    19. }
    floating_point_imprecision.png

    Your mileage almost certainly will vary. Choose an epsilon term and know it well.
     
    twobob likes this.
  5. twobob

    twobob

    Joined:
    Jun 28, 2014
    Posts:
    2,058
    It's posts like this that make me glad I do Stupid mistakes.

    I would <3 this twice if I could
     
    Kurt-Dekker likes this.