Reputation: 836
I need to take a series of radian values and convert them to be in the interval of -pi to pi.
Here is the function for singular values
def angle_truncation(angle):
while angle < 0.0:
angle += np.pi * 2
return ((angle + np.pi) % (np.pi * 2)) - np.pi
angle = 5.
print(angle_truncation(angle))
>> -1.28318530718
Because of the while loop though this won't work as is with numpy arrays. So would the above function be converted to work with numpy arrays using vectorization/broadcasting instead of just adding in a for loop?
ie
a = np.fill((3, 1), 5.)
print(angle_truncation(a))
>> [[-1.28318530718, -1.28318530718, -1.28318530718]]
Upvotes: 1
Views: 479
Reputation: 947
How about calculating the fraction of pi and then adding the resulting multiple of it to the array.
import numpy as np
def angle_trunc(array) :
below_pi = array < np.pi
fractions = np.abs(array[below_pi]) / (2 * np.pi)
array[below_zero] += np.ceil(fractions) * (2 * np.pi)
return (array % (2 * np.pi)) - np.pi
Upvotes: 1
Reputation: 16404
This while
loop is needless, you only need to take the ceil()
of the quotient:
angle_trunc = lambda a: (a+np.ceil(abs(a)/(2*np.pi))*2*np.pi+np.pi)%(np.pi*2) - np.pi
Upvotes: 1