简体   繁体   中英

The arctangent of tangent x is not calculated precisely

I need tangent, arctangent functions for my Python program. I tried np.arctan and np.tan but observed a strange behaviour. In principle, the arctangent of tangent of some number is the number itself, but the code below doesn't give a precise value.

import numpy as np
x = 10
print(np.arctan(np.tan(x)))

When I change x to 2*x or 3*x, then the result is even more inaccurate. I tried math.tan, math.atan but the result was the same.

Can someone please explain why it happens(which of the two functions is wrong), and under which condition one should be careful about using the arctangent and tangent functions?

three things to note:

  1. in python (as in all programming languages i have ever looked at) trigonometric functions work with angles in radians ie the range [0, 2*pi) represents the 'full circle'
  2. tan is periodic: tan(x) = tan(pi + x) (again note that this is in radians; in python tan(x) = tan(180 + x) will not be true!).
  3. arctan returns a value in [-pi/2, pi/2) .

in your example you fall back on the correct result in [-pi/2, pi/2) :

import numpy as np

x = 10
print(np.arctan(np.tan(x)))  # 0.575222039231
print(10 % (np.pi / 2))      # 0.5752220392306207

your function np.arctan(np.tan(x)) is equivalent to (the computationally less expensive)

def arctan_tan(x):
    ret = x % np.pi
    if ret > np.pi / 2:
        ret -= np.pi
    return ret

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM