harmegiddo
harmegiddo

Reputation: 35

Why is the result of trigonometric function calculation different?

I calculated three methods of the following with Numpy.

Avoiding the circle periodicity, I given the range is 0 to +180. The calculation results of the three methods should match.

However, all calculation results are different. Why is this?

degAry = []
sumDeg = 0
cosRad = 0
sinRad = 0
LEN = 300
RAD2DEG = 180.0 / PI    # 57.2957795
for i in range(LEN):
      deg = random.uniform(0,180)
      rad = np.deg2rad(deg)
      degAry.append(deg)
      sumDeg += deg
      cosRad += np.cos(rad)
      sinRad += np.sin(rad)

print(np.arctan2( sinRad/LEN, cosRad/LEN ) * RAD2DEG) # 88.39325364335279
print(np.sum(degAry)/LEN) # 88.75448888951954
print(sumDeg/LEN) # 88.75448888951951

Upvotes: 0

Views: 132

Answers (2)

NaN
NaN

Reputation: 2312

EDIT Mean of circular quantities suggesting that the sin, cos approach is best.

Refactoring your code to use numpy exclusively. The two methods are different, however, the first two using RAD2DEG or the np.degrees yield the same results. The latter which used the sum of degrees divided by sample size differs.

It doesn't appear to be a summation issue (N=3000, sum in normal order, ascending then descending). They yield the same results

np.sum(deg)                # 134364.25172174018
np.sum(np.sort(deg))       # 134364.25172174018
np.sum(np.sort(deg)[::-1]) # 134364.25172174018

I didn't carry it out with the summation for the cos and sin in radian form. I will leave that for others.

PI = np.pi
sumDeg = 0.
cosRad = 0.
sinRad = 0.
N = 30
RAD2DEG = 180.0 / PI    # 57.2957795
deg = np.random.uniform(0, 90.0, N)
rad = np.deg2rad(deg)
sumDeg = np.sum(deg)
cosRad = np.sum(np.cos(rad))
sinRad = np.sum(np.sin(rad))
print(np.arctan2(sinRad/N, cosRad/N) * RAD2DEG)
print(np.degrees(np.arctan2(sinRad/N, cosRad/N)))
print(sumDeg/N)

Results for

> N = 1
> 22.746571717879792
> 22.746571717879792
> 22.746571717879792
> 
> N= 30
> 48.99636699165551
> 48.99636699165551
> 49.000295118106884
> 
> N = 300
> 44.39333460088003
> 44.39333460088003
> 44.44513528547155
> 
> N = 3000
> 44.984167020219175
> 44.984167020219175
> 44.97574462726241

Upvotes: 0

Paul Panzer
Paul Panzer

Reputation: 53029

What makes you think that the mean angle and the angle of the mean vector should be the same? This is correct only for n = 1,2, for n = 3 degAry = [0, 90, 90] is easily verified to be a counter example: mean of the angles is 60 with tan = sqrt(3), mean vector is (1/3 2/3) corresponding to tan = 2.

Upvotes: 1

Related Questions