Harvesine formula returning NaN

Hi! I am trying to get the Harvesine formula to work, but it seems to be returning a NaN value (not a number?).
Can you help me plz?

	public float haversineDist(Vector3 pos1, Vector3 pos2)

  {
	//Centers the coordinates to the central point of the sphere
	  pos1 =pos1-centralPoint;
	  pos2 =pos2-centralPoint;
	  
	//Gets the spherical coordinates of the two points  
	Vector2 pos3=new Vector2(Mathf.Acos(pos1.z/radius), Mathf.Atan(pos1.y/pos1.x));
	Vector2 pos4=new Vector2(Mathf.Acos(pos2.z/radius), Mathf.Atan(pos2.y/pos2.x));
	  

    float dLat = Mathf.Deg2Rad * (pos4.x - pos3.x);

    float dLon = Mathf.Deg2Rad * (pos4.y - pos3.y);

//Harvesine distance
float d = 2*radius* Mathf.Asin(Mathf.Sqrt(Mathf.Sin(dLat/2)*Mathf.Sin(dLat/2)+ Mathf.Cos(pos3.x)*Mathf.Cos(pos4.x)*Mathf.Sin(dLon/2)*Mathf.Sin(dLon/2)));

//This print is to check if it is NaN   
	  print(d);
	  
	  return d;
  }

Ty for your time.
Dydra

I didn’t look at the actual values, but my best guess is that Mathf.Sqrt is NaN when the parameter is negative. I dont see anything that prevents all the sin, cos and tan from becoming negative, so thats what I’m putting my money on. :wink:

Edit: Ok, I actually looked up the formula, hoping to find some Abs. But your version of the formula seems fine. The only thing (since everything else is squared) that could possible cause Sqrt to become negative would be

Mathf.Cos(pos3.x)*Mathf.Cos(pos4.x)

Maybe print that out seperately?

both

	  print(Mathf.Sin(dLat/2)*Mathf.Sin(dLat/2));
	  print(Mathf.Cos(pos3.x)*Mathf.Cos(pos4.x));

Are returning NaN…

Well the first has to be NaN if the second is, since they are multiplied earlier. Honestly radius has gotta be NaN. Else im stomped.