Skip to content

Commit ff8aa26

Browse files
author
Sylvain Guillet
committed
Improve robustness of Vector3.Angle method
Updated the Vector3.Angle method to handle zero vectors and mitigate floating-point precision errors. Added checks for zero magnitudes, clamped dot product to [-1, 1], and ensured numerical stability for edge cases.
1 parent 83bd313 commit ff8aa26

File tree

1 file changed

+15
-1
lines changed
  • IO.Astrodynamics.Net/IO.Astrodynamics/Math

1 file changed

+15
-1
lines changed

IO.Astrodynamics.Net/IO.Astrodynamics/Math/Vector3.cs

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,21 @@ public Vector3 Cross(in Vector3 vector)
4646

4747
public double Angle(in Vector3 vector)
4848
{
49-
return System.Math.Acos(this * vector / (Magnitude() * vector.Magnitude()));
49+
var mag1 = Magnitude();
50+
var mag2 = vector.Magnitude();
51+
52+
// Handle zero vectors
53+
if (mag1 == 0.0 || mag2 == 0.0)
54+
{
55+
return 0.0; // Angle is undefined, return 0 by convention
56+
}
57+
58+
var dotProduct = (this * vector) / (mag1 * mag2);
59+
60+
// Clamp to [-1, 1] to handle floating-point precision errors
61+
dotProduct = System.Math.Clamp(dotProduct, -1.0, 1.0);
62+
63+
return System.Math.Acos(dotProduct);
5064
}
5165

5266
public double Angle(in Vector3 vector, in Plane plane)

0 commit comments

Comments
 (0)