performance - Fastest way to sort vectors by angle without actually computing that angle -


many algorithms (e.g. graham scan) require points or vectors sorted angle (perhaps seen other point, i.e. using difference vectors). order inherently cyclic, , cycle broken compute linear values doesn't matter much. real angle value doesn't matter either, long cyclic order maintained. doing atan2 call every point might wasteful. faster methods there compute value strictly monotonic in angle, way atan2 is? such functions apparently have been called “pseudoangle” some.

i started play around , realised spec kind of incomplete. atan2 has discontinuity, because dx , dy varied, there's point atan2 jump between -pi , +pi. graph below shows 2 formulas suggested @mvg, , in fact both have discontinuity in different place compared atan2. (nb: added 3 first formula , 4 alternative lines don't overlap on graph). if added atan2 graph straight line y=x. seems me there various answers, depending on 1 wants put discontinuity. if 1 wants replicate atan2, answer (in genre)

# input:  dx, dy: coordinates of (difference) vector. # output: number range [-2 .. 2] monotonic #         in angle vector makes against x axis. #         , same discontinuity atan2 def pseudoangle(dx, dy):     p = dx/(abs(dx)+abs(dy)) # -1 .. 1 increasing x     if dy < 0: return p - 1  # -2 .. 0 increasing x     else:      return 1 - p  #  0 .. 2 decreasing x 

this means if language you're using has sign function, avoid branching returning sign(dy)(1-p), has effect of putting answer of 0 @ discontinuity between returning -2 , +2. , same trick work @mvg's original methodology, 1 return sign(dx)(p-1).

update in comment below, @mvg suggests one-line c implementation of this, namely

pseudoangle = copysign(1. - dx/(fabs(dx)+fabs(dy)),dy) 

@mvg says works well, , looks me :-).

enter image description here


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -