Search code examples
numericangleepsilon

arccos((sin(x)^2)+cos(x)^2) is not 0 for certain angles


I am struggling with a simple calculation problem.

By theory for an arbitrary angle:

If

is

enter image description here

If I implement this in python or Matlab:

import numpy as np

alpha = -89.999961

alpha_rad =  np.deg2rad(alpha)
result = np.arccos(np.sin(alpha_rad)**2 + np.cos(alpha_rad)**2)

print('%.16f' % result)

leads to

0.0000000149011612

whereas

alpha = -89.9999601

leads to

0.0000000000000000

It is also practically 0 using -89.999962°, but it is again 1.49011612e-08 for alpha = -89.9999°

Does anybody know the reason for this and which angles will lead to results bigger than 0. I am not an big expert in numerical mathematics, but the spacing of floating numbers is much smaller (2.220446049250313e-16). I want to multiply the result with a large number so it would be great, if the result is 0 in terms of floating numbers spacing.

Any help and explanation is very welcome!


Solution

  • solves the problem for arbitrary angles. Cosines is known for numerical problems (e.g. https://www.nayuki.io/page/numerically-stable-law-of-cosines)