Python math.cos() 方法



Python 的 math.cos() 方法用於計算以弧度表示的角度的餘弦值。在數學上,餘弦函式定義為直角三角形中鄰邊與斜邊的比值;其定義域可以是所有實數。當我們將浮點數以外的任何內容作為引數傳遞給它時,此方法會引發 TypeError。

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

語法

以下是 Python math.cos() 方法的語法 -

math.cos(x)

引數

  • x - 這必須是一個數值。

返回值

此方法返回一個介於 -1 和 1 之間的數值,表示角度的餘弦值。

示例

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

import math

# If the cosine angle is pi
x = 3.14
cosine = math.cos(x)
print("The cosine value of x is:", cosine)

# If the cosine angle is pi/2
x = 3.14/2
cosine = math.cos(x)
print("The cosine value of x is:", cosine)

# If the cosine angle is 0
x = 0
cosine = math.cos(x)
print("The cosine value of x is:", cosine)

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

The cosine value of x is: -0.9999987317275395
The cosine value of x is: 0.0007963267107332633
The cosine value of x is: 1.0

示例

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

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

import math

# If the cosine angle is pi
x = 5.48
cosine = math.cos(x)
print("The cosine value of x is:", cosine)

# If the cosine angle is pi/2
x = 1.34
cosine = math.cos(x)
print("The cosine value of x is:", cosine)

# If the cosine angle is 0
x = 0.78
cosine = math.cos(x)
print("The cosine value of x is:", cosine)

如果我們編譯並執行給定的程式,則輸出將顯示如下 -

The cosine value of x is: 0.6944181792510162
The cosine value of x is: 0.22875280780845939
The cosine value of x is: 0.7109135380122773

示例

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

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

import math

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

在執行以上程式時,輸出將顯示如下 -

Traceback (most recent call last):
  File "main.py", line 5, in 
    cosine = math.cos(x)
TypeError: can't convert complex to float

示例

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

在以下示例中,我們建立了一個數字物件,該物件以度數儲存餘弦角。由於 cos() 方法採用弧度作為引數,因此我們可以對該物件呼叫 radians() 方法將其轉換為相應的弧度值。然後,我們將此弧度值作為引數傳遞給此方法並找到其餘弦比。

import math

# Take the cosine angle in degrees
x = 60

# Convert it into radians using math.radians() function
rad = math.radians(x)

# Find the cosine value using cos() method
cosine = math.cos(rad)

# Display the cosine ratio
print("The cosine value of x is:", cosine)

以上程式的輸出如下 -

The cosine value of x is: 0.5000000000000001
python_maths.htm
廣告