1

The built-in VectorAngle function sometimes returns complex output when the actual angle is very close to π. The imaginary component is large enough and can't be removed by Chop with default tolerance:

VectorAngle[{0.034429687500000083, 0}, {-0.03442968749999986, 0}]
%//Chop
3.141592653589793` - 2.1073424338879928`*^-8 I

3.141592653589793- 2.1073424338879928*^-8 I

For comparison, custom implementation works as expected:

vectorAngle[v1_, v2_] := ArcCos[v1.v2/(Norm[v1] Norm[v2])]

vectorAngle[{0.034429687500000083, 0}, {-0.03442968749999986, 0}]
3.141592653589793` 

From where comes imaginary part in the output? Is it a bug?

m_goldberg
  • 107,779
  • 16
  • 103
  • 257
Alexey Popkov
  • 61,809
  • 7
  • 149
  • 368

1 Answers1

3

Use higher precision:

VectorAngle @@ SetPrecision[#, 20]& @ {
  {0.034429687500000083, 0}, {-0.03442968749999986, 0}}

(*  3.141592654  *)

EDIT: High precision isn't required, just setting a precision to avoid machine precision provides a real value:

Table[
 VectorAngle @@ SetPrecision[#, p] &@
  {{0.034429687500000083, 0},
   {-0.03442968749999986, 0}},
 {p, 5, 25, 5}]

(*  {3.1, 3.1416, 3.141593, 3.141592654, 3.14159265359}  *)
Bob Hanlon
  • 157,611
  • 7
  • 77
  • 198