Python math.log() 方法



Python 的 math.log() 方法用於計算正數值的自然對數(以 e 為底)。

對數的一般和簡單的定義是指數的逆運算。這意味著,對數的結果是底數要提升到的冪。因此,此方法的結果始終是浮點數。

以 'e' 為底的對數可以表示如下

logba = p

其中,

  • a: 任何數字
  • b: 對數的底數
  • p: 底數提升到的冪

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

語法

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

math.log( x )

引數

  • x - 這必須是正數值。

返回值

此方法返回 x 的自然對數,其中 x > 0。

示例

以下示例顯示了 Python math.log() 方法的使用。我們在這裡將正值作為引數傳遞給此方法,因此結果也將是正浮點數。

import math # This will import the math module

# Create a numeric object
x = 36.789

# Calculate the natural logarithm of x
ln = math.log(x)

# Display the log value
print("The logarithm of x is:", ln)

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

The logarithm of x is: 3.6051988874479988

示例

但是,如果我們將負值作為引數傳遞給此方法,則會引發 ValueError,因為自然對數的定義域僅為正實數。

import math # This will import the math module

# Create a numeric object
x = -76.43

# Calculate the natural logarithm of x
ln = math.log(x)

# Display the log value
print("The logarithm of x is:", ln)

如果我們編譯並執行上面的程式,則輸出顯示如下:

Traceback (most recent call last):
  File "main.py", line 7, in 
    ln = math.log(x)
ValueError: math domain error

示例

此方法也不接受數值以外的引數。

在以下示例中,讓我們建立一個包含數值的列表並將其作為引數傳遞給此方法。由於列表是可迭代物件,因此預計會引發 ValueError。

import math # This will import the math module

# Create a list object
x = [12, 45.68, 112, 66.33]

# Calculate the natural logarithm of x
ln = math.log(x)

# Display the log value
print("The logarithm of x is:", ln)

如果我們執行上面的程式,則會引發以下 ValueError:

Traceback (most recent call last):
  File "main.py", line 7, in 
ln = math.log(x)
TypeError: must be real number, not list

示例

但是,我們可以使用迴圈語句迭代上面示例中給出的列表,並找到其中存在的數值的自然對數。

import math # This will import the math module

# Create a list object
x = [12, 45.68, 112, 66.33]

# Using a for loop, iterate through the list
for n in range(0, len(x)):
   # Calculate the natural logarithm of x
   ln = math.log(x[n])
   # Display the log value
   print("The logarithm of x[",n,"] is:", ln)

在編譯並執行上述程式後,結果如下:

The logarithm of x[ 0 ] is: 2.4849066497880004
The logarithm of x[ 1 ] is: 3.821660565347755
The logarithm of x[ 2 ] is: 4.718498871295094
The logarithm of x[ 3 ] is: 4.194642283537465

示例

此 log() 方法與 exp() 方法完全相反。這意味著,log() 方法的引數是 exp() 方法的返回值。

在此示例中,我們正在建立一個物件 'x' 並將其作為引數傳遞給 exp() 方法。從此方法獲得的返回值儲存在另一個變數 'var' 中。現在,如果儲存在 'var' 中的值作為引數傳遞給 log() 方法,則預期返回值將是儲存在 'x' 中的值。

import math # This will import the math module

# Create a list object
x = 12.34

# Pass x as an argument to the exp() method
var = math.exp(x)

print("The exponent value of x is:", var)

# Calculate the natural logarithm of x
ln = math.log(var)

# Display the log value
print("The logarithm of x is:", ln)

上面程式的輸出顯示如下:

The exponent value of x is: 228661.9520568098
The logarithm of x is: 12.34
python_maths.htm
廣告