Java Atan2() Sort violates general contract?

97 views Asked by At

I'm having trouble with a comparison method being used in Java/Processing.

It says it violates its general contract, which I understand means it doesn't work on the relationships between the items consistently...

But I don't understand why. Since it just returns the angle, theta, based on the ratio of ycor to xcor (like sin to cos), shouldn't it sort them consistently based on their positions from 0 to 360 degrees?

public int compareTo(Orb other) {
double X = Math.atan2(ycor,xcor);
if (Math.atan2(other.ycor,other.xcor) > X) {
  return -1;
}
if (Math.atan2(other.ycor,other.xcor) == X) {
  return 0;
}
return 1;
}

Any help is very appreciated, thanks!

The specific context is that the error occurs when a Collection.Sort() is run.

1

There are 1 answers

5
Jakob Weisblat On

EDIT: See Louis Wasserman's comment above:

Is it possible that xcor and ycor are both zero for some of these? I suspect that would result in NaN. Switching to Double.compare(Math.atan2(ycor, xcor), Math.atan2(other.ycor, other.xcor)) ought to work.

THE BELOW WAS THE CONTENT OF THIS POST; IT IS PROBABLY WRONG

It's not well-defined whether one angle is "greater" than another - if I'm clockwise of you by 170 degrees, then I'm also counterclockwise of you by 190 degrees.

Even if you choose to use "within 180 degrees of" as greater-than, you still don't have the triangle inequality satisfied.