Python math.log10() 方法



Python math.log10() 方法用於獲取給定數字以 10 為底的對數。

根據數學定義,一個數字的對數函式產生一個結果,該結果與其底數相乘以達到所述數字。然而,在通常的對數中,底數可以是任何值,但對於此方法,我們只取底數為 10。

換句話說,此方法為我們提供了任何值的以 10 為底的對數。它遵循以下公式:

log10a = result

語法

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

math.log10(x)

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

引數

  • x - 這是一個數字表達式。

返回值

此方法返回 x(x > 0)的以 10 為底的對數。

示例

以下示例顯示了 Python math.log10() 方法的用法。這裡我們將正數作為引數傳遞給 log10() 方法。

# importing the math module
import math   
print ("math.log10(100.12) : ", math.log10(100.12))
print ("math.log10(100.72) : ", math.log10(100.72))
print ("math.log10(math.pi) : ", math.log10(math.pi))

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

math.log10(100.12) :  2.00052084094
math.log10(100.72) :  2.0031157171
math.log10(math.pi) :  0.497149872694

示例

在下面的程式碼中,我們建立了一個數字元組和一個數字列表。然後,在 log10 方法中,我們嘗試查詢元組中索引 3 處的數值和列表中索引 2 處的數值的對數。

import math
# Creating a tuple
Tuple = (7, 83, -34, 26, -84)
# Crating a list
List = [8, -35, 56.34, 2, -46] 
print('The log10() value of Tuple Item is:', math.log10(Tuple[3]))
print('The log10() value of List Item is:', math.log10(List[2]))

上述程式碼的輸出如下:

The log10() value of Tuple Item is: 1.414973347970818
The log10() value of List Item is: 1.7508168426497546

示例

如果我們將字串作為引數傳遞給此方法,則會返回 TypeError。

在以下示例中,我們檢索作為引數傳遞給 log10() 方法的多個值的 log10 值。我們還嘗試檢索字串的 log10 值。

import math
num = 34 + 5837 - 334
num2 = 'TutorialsPoint'
res = math.log10(num)
print('The log10() value of multiple numbers is:', res)
print('The log10() value of a string is:', math.log(num2))

執行上述程式碼時,我們得到如下所示的輸出:

The log10() value of multiple numbers is: 3.7432745235119333
Traceback (most recent call last):
  File "C:\Users\Lenovo\Desktop\untitled.py", line 6, in <module>
    print('The log10() value of a string is:', math.log(num2))
TypeError: must be real number, not str

示例

如果我們將零作為引數傳遞給此方法,則會引發 ValueError。

import math
num = 0.0
res = math.log10(num)
print('The result for num2 is:', res)

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

Traceback (most recent call last):
  File "C:\Users\Lenovo\Desktop\untitled.py", line 3, in <module>
    res = math.log10(num)
ValueError: math domain error

示例

當我們將負值作為引數傳遞給此方法時,會引發 ValueError

import math
# negative number
num = -76
res = math.log10(num)
print('The result for num2 is:', res)

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

Traceback (most recent call last):
  File "C:\Users\Lenovo\Desktop\untitled.py", line 4, in <module>
    res = math.log10(num)
ValueError: math domain error
python_maths.htm
廣告