切线x的反正切不能精确计算

Now*_*uri 2 python math trigonometry numpy python-3.x

我的Python程序需要切线,反正切函数。我尝试了np.arctan和np.tan,但是观察到了奇怪的行为。原则上,某个数字的切线的反正切是数字本身,但是下面的代码没有给出精确的值。

import numpy as np
x = 10
print(np.arctan(np.tan(x)))
Run Code Online (Sandbox Code Playgroud)

当我将x更改为2 * x或3 * x时,结果将更加不准确。我尝试了math.tan,math.atan,但是结果是一样的。

有人可以解释为什么会发生这种情况(两个函数中的哪个是错误的),在哪种情况下应谨慎使用反正切和正切函数?

hir*_*ist 5

需要注意的三件事:

  1. 在python中(就像我曾经看过的所有编程语言一样),三角函数以弧度表示角度,即范围[0, 2*pi)代表“完整的圆”
  2. tan是周期性的:(tan(x) = tan(pi + x)再次注意,这是弧度;在python tan(x) = tan(180 + x)中将不成立!)。
  3. arctan返回中的值[-pi/2, pi/2)

在您的示例中,您将退回到正确的结果[-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
Run Code Online (Sandbox Code Playgroud)

您的功能np.arctan(np.tan(x))相当于(在计算上更便宜)

def arctan_tan(x):
    ret = x % np.pi
    if ret > np.pi / 2:
        ret -= np.pi
    return ret
Run Code Online (Sandbox Code Playgroud)