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

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:
    38,520
    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.