I'm working with a data set of accelerations using python 2.7, in order to find the angle, I'm using arctan2(y,x). My problem is that, while my data can rotate beyond pi, the output of arctan2(y,x) is bounded between pi and -pi. This means any time I go above pi, I suddenly have a dramatic jump in my data and loop to negative pi.
I'm trying to figure out an elegant solution to fix this and make my graph continuous. I've implemented a simple check where if I even jump more than about 80% of the way, I assume I've gone out of bounds and start adding 2 pi to every subsequent data point. This works but feels very clunky. Is there a more elegant way to implement this? Or is this the best I can do?
Thank you ^_^
for index in range(1,(len(x_data))):
new_angle = math.atan2((y_data[index]), (x_data[index]))
if (new_angle - angle[index-1]) > 5:
new_angle = new_angle - 6.28
if (new_angle - angle[index-1]) < -5:
new_angle = new_angle + 6.28
angle.append(new_angle)
Green shows what I want, black shows what I get
While the function atan2 is discontinuous along the negative x-axis, reflecting the fact that angle cannot be continuously defined, this derivative is continuously defined except at the origin, reflecting the fact that infinitesimal (and indeed local) changes in angle can be defined everywhere except the origin.
The atan2() function returns a value in the range -π to π radians. If both arguments of the atan2() function are zero, the function sets errno to EDOM, and returns a value of 0.
In conclusion, if you are calculating something that ranges between -90 and 90 degrees like latitude, use arctan. If calculating an angle that can be between -180 and 180 degrees, use arctan2.
Element-wise arc tangent of x1/x2 choosing the quadrant correctly. The quadrant (i.e., branch) is chosen so that arctan2(x1, x2) is the signed angle in radians between the ray ending at the origin and passing through the point (1,0), and the ray ending at the origin and passing through the point (x2, x1).
What you're trying to do is normally called "lifting"... the code I use is
last = 0
out = []
for x, y in data:
angle = math.atan2(y, x)
while angle < last-math.pi: angle += 2*math.pi
while angle > last+math.pi: angle -= 2*math.pi
last = angle
out.append(angle)
The two "while" loops could be condensed in the more cryptic
angle = (angle-last + math.pi)%(2*math.pi)-math.pi + last
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With