-1

I am getting an unexpected result from Vector3.Distance function, could someone please explain what is going on here:

I create two vectors using two angles and a radius, when angles are 0 and 360 degrees, I expected the distance to be 0, but it is not. Here is the code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[ExecuteInEditMode]
public class test : MonoBehaviour
{
public float angle1 = 0f;
public float angle2 = 360f;
public float radius = 1f;
private Vector3 position1, position2;


// Update is called once per frame
void Update()
{
    // calculate position vector from given angle
    position1 = new Vector3(0, Mathf.Sin(Mathf.Deg2Rad * angle1), Mathf.Cos(Mathf.Deg2Rad * angle1)) * radius;
    position2 = new Vector3(0, Mathf.Sin(Mathf.Deg2Rad * angle2), Mathf.Cos(Mathf.Deg2Rad * angle2)) * radius;
    float distance = Vector3.Distance(position1, position2);

    print("angle1: " + angle1 + " angle2: " + angle2);
    print("pos1: " + position1 + " pos2: " + position2);
    print("positions equal: " + (position1 == position2));
    print("distance: " + distance);
   }
}

This outputs the following:

angle1: 0 angle2: 360
pos1: (0.0, 0.0, 1.0) pos2: (0.0, 0.0, 1.0)
positions equal: True
distance: 1.748456E-07

Any help is apprecited.

B-and-P
  • 1,693
  • 10
  • 26

1 Answers1

1

It is not quite unexpected. It is just how the data type float can operate at times due to floating point precision. You would want to compare the values using an epsilon or by using a function built into unity called Mathf.Approximately, which is equivalent to an epsilon check.

Based on Unity's docs of Vector3.Distance, the implementation is the same as the magnitude of the difference of two vectors. From your example, the result would clearly be (0.0, 0.0, 0.0), and the magnitude should be √(x^2+y^2+z^2), which would be √(0) or just 0. Now, the answer that Vector.Distance has outputted is 1.748456E-07, or 1.748456*(10^-07), which is 0.000000175. If we use Mathf.Approximately using 0, your expected answer and the answer the function gave you, 0.000000175, the are approximately the same value.

Edit: Just tested it and whatever epsilon that Unity uses for Mathf.Approximately is smaller than 0.000000175, so it actually returns false. The reason as to why it returns such a value would still stand though.

TEEBQNE
  • 6,104
  • 3
  • 20
  • 37
  • 1
    You can simply look at the [source code](https://github.com/Unity-Technologies/UnityCsReference/blob/61f92bd79ae862c4465d35270f9d1d57befd1761/Runtime/Export/Math/Mathf.cs#L284) and see that Unity uses some strange construct `Abs(b - a) < Max(0.000001f * Max(Abs(a), Abs(b)), Epsilon * 8)` where Epsilon is either `1.17549435E-38f` or `Single.Epsilon` (=`1.401298E-45`) depending on the system ;) – derHugo Sep 01 '21 at 10:05
  • @derHugo Interesting wasn't aware it was available. Very odd indeed. Bookmarked - thanks for the resource! – TEEBQNE Sep 01 '21 at 17:45