Python math.tan() 方法



Python math.tan() 方法用於計算以弧度表示的角度的正切值。從數學上講,正切函式定義為直角三角形中給定角度的對邊與鄰邊的比值。

最常用的正切值是 0、30、45、60 和 90 度角的正切值。正切函式的值域是所有實數。當我們將除浮點數以外的任何內容作為引數傳遞給它時,此方法會引發 TypeError。

注意 - 此函式無法直接訪問,因此我們需要匯入 math 模組,然後需要使用 math 靜態物件呼叫此函式。

語法

以下是 Python math.tan() 方法的語法:

math.tan(x)

引數

  • x - 必須是數值。

返回值

此方法返回一個實數,表示角度的正切值。

示例

以下示例顯示了 Python math.tan() 方法的使用方法。在這裡,我們嘗試傳遞標準正切角並使用此方法找到它們的三角正切比。

import math
print ("tan(3) : ",  math.tan(3))
print ("tan(-3) : ",  math.tan(-3))
print ("tan(0) : ",  math.tan(0))
print ("tan(math.pi) : ",  math.tan(math.pi))
print ("tan(math.pi/2) : ",  math.tan(math.pi/2))
print ("tan(math.pi/4) : ",  math.tan(math.pi/4))

當我們執行上述程式時,它會產生以下結果:

tan(3) :  -0.142546543074
tan(-3) :  0.142546543074
tan(0) :  0.0
tan(math.pi) :  -1.22460635382e-16
tan(math.pi/2) :  1.63317787284e+16
tan(math.pi/4) :  1.0

示例

不僅是標準角度,此方法還可以用於查詢非標準角度的正切比。

在此示例中,我們建立了多個數字物件,這些物件以弧度儲存非標準角度。這些值作為引數傳遞給此方法,以找到它們的最終正切比。

import math
# If the tangent angle is pi
x = 5.48
tangent = math.tan(x)
print("The tangent value of x is:", tangent)
# If the tangent angle is pi/2
x = 1.34
tangent = math.tan(x)
print("The tangent value of x is:", tangent)
# If the tangent angle is 0
x = 0.78
tangent = math.tan(x)
print("The tangent value of x is:", tangent)

執行上述程式碼時,我們得到以下輸出:

The tangent value of x is: -1.0362224007393084
The tangent value of x is: 4.255617891739467
The tangent value of x is: 0.989261536876605

示例

即使複數仍被視為數字,此方法也只接受實數作為引數。

讓我們看一下將複數作為引數傳遞給 tangent() 方法的情況。該方法會引發 TypeError。

import math
# If the tangent angle is a complex number
x = 12-11j
tangent = math.tan(x)
print("The tangent value of x is:", tangent)

以下是上述程式碼的輸出:

Traceback (most recent call last):
  File "C:\Users\Lenovo\Desktop\untitled.py", line 4, in <module>
    tangent = math.tan(x)
TypeError: must be real number, not complex

示例

我們可以使用 math.radians() 方法將度數轉換為弧度,並將其作為引數傳遞給 tan() 方法。

在下面的示例中,我們建立了一個數字物件,用於儲存以度為單位的正切角。由於 tan() 方法接受以弧度為單位的引數,因此我們可以呼叫此物件上的 radians() 方法將其轉換為相應的弧度值。然後,我們將此弧度值作為引數傳遞給此方法,並找到其正切值。

import math
# Take the tangent angle in degrees
x = 60
# Convert it into radians using math.radians() function
rad = math.radians(x)
# Find the tangent value using tan() method
tangent = math.tan(rad)
# Display the tangent ratio
print("The tangent value of x is:", tangent)

上述程式碼的輸出如下所示:

The tangent value of x is: 1.7320508075688767
python_maths.htm
廣告