Search Unity

Why is Mathf.Approximately(Infinity, Infinity) returning false?

Discussion in 'Scripting' started by ArachnidAnimal, Jul 11, 2019.

  1. ArachnidAnimal

    ArachnidAnimal

    Joined:
    Mar 3, 2015
    Posts:
    1,632
    I'm running into an issue where this equivalent code
    Code (csharp):
    1.  
    2. Mathf.Approximately(Mathf.Infinity, Mathf.Infinity)
    3.  
    is returning false.

    If I'm not mistaken, this should be evaluated as true as the floats are equal
    Is this a bug in the API?
     
  2. Lurking-Ninja

    Lurking-Ninja

    Joined:
    Jan 20, 2015
    Posts:
    3,883
    No. Infinity is not a number.
    Infinity = infinity is not something you can determinate. The only assumption you can have is Infinity is > than any number.

    On the top of that, Mathf.Approximately is this:
    https://docs.unity3d.com/ScriptReference/Mathf.Approximately.html
     
    ArachnidAnimal likes this.
  3. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    6,509
    Math.Approximately effectively is just:
    Code (csharp):
    1. Abs(a - b) < Epsilon
    Where epsilon is a tiny value (like 0.0001)

    So what you're asking is:
    Code (csharp):
    1. Abs(inf - inf) < Epsilon
    But what is (inf - inf)?

    How can you subtract infinity from infinity?

    In the IEEE 754 floating point standard (what is used in unity for floats), inf - inf = NaN. And NaN always compares false (even to itself... NaN != NaN)
     
    ArachnidAnimal likes this.
  4. ArachnidAnimal

    ArachnidAnimal

    Joined:
    Mar 3, 2015
    Posts:
    1,632
    I guess I always assumed that Mathf.Infinity was actually just returning float.MaxValue.
    Apparently this is not the case.

    Unity API:
    public const float Infinity = float.PositiveInfinity;

    C# System.Single:
    public const float MaxValue = 3.402823E+38;
    public const float PositiveInfinity = ∞; //Unknown value?


    The "==" evaluation is working for this situation.
    Code (csharp):
    1.  
    2. var val1= Mathf.Infinity;
    3.  var val2= Mathf.Infinity;
    4.  
    5.   if (val1 ==val2)
    6.    {
    7.           //Is evaluating to true
    8.     }
    9.  
    Is there some other way to reliably check for this?
     
  5. ArachnidAnimal

    ArachnidAnimal

    Joined:
    Mar 3, 2015
    Posts:
    1,632
    "Overriding" getting the remaining distance of a NavMeshAgent due to the Unity API returning 0 when the path is still being calculated. So basically the remaining distance is invalid if the path calculation is still being performed.
    Code (csharp):
    1.  
    2. private float GetRemainingDistance ()
    3.     {
    4.         if (agent.pathPending) {        
    5.             return +Mathf.Infinity;
    6.         } else {
    7.             return agent.remainingDistance;
    8.         }
    9.     }
    10.  
    11. if (GetRemainingDistance() == Mathf.Infinity)
    12. {
    13. //...
    14. }
    15.