Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Float Comparisons

Discussion in 'Scripting' started by SecondDegreePerm, May 16, 2020.

  1. SecondDegreePerm

    SecondDegreePerm

    Joined:
    Jul 2, 2017
    Posts:
    42
    I am having an issue where comparing two floats seems to return nonsensical results. I have two floats, mid and curHeight, than I am comparing to each other. See below:

    Code (CSharp):
    1.  Debug.Log("pre gravity " + "mid" + mid.ToString("F32") + "  curheight" + curHeight.ToString("F32"));
    2.         if (mid < curHeight)
    3.         {
    4.             Debug.Log("applying gravity");
    5.             timeInAir += 1 * Time.deltaTime;
    6.             verticalHeight -= gravity * Time.deltaTime;
    7.         }

    upload_2020-5-16_12-50-11.png
    How can it be possible that the mid variable can be less than the curHeight float when they are evidently the same? I have well surpassed the digits of accuracy that a float provides here. Moreover, why is it only seen as less than some of the time and not others? 3 of the 567 times true must have been returned, despite the fact the other 564 times the same value was compared.

    I have been rather stumped on this for a while, any help would be appreciated. I am happy to answer any questions and provide more information if it is required.

    Thanks in advance
     
  2. sama-van

    sama-van

    Joined:
    Jun 2, 2009
    Posts:
    1,723
    SecondDegreePerm likes this.
  3. SecondDegreePerm

    SecondDegreePerm

    Joined:
    Jul 2, 2017
    Posts:
    42
    I believe this has worked, though part of me is still frustrated that values that show as equivalent are not treated as equivalent! Thanks for the help