Python math.log1p() 方法



Python 的 math.log1p() 方法用於計算 1 + x 的自然對數,其中 x 是傳遞給該方法的引數。從數學上講,該方法表示為:

\log1p\:(x)\:=\:\log_{e}({1\:+\:x})\:=\:\ln(1\:+\:x)

其中,e 是自然對數的底(尤拉數)。例如,如果 x = 1,則 math.log1p(1) 返回 ln(1 + 1),簡化為 ln(2)。

注意:要使用此函式,您需要匯入 math 模組

語法

以下是 Python math.log1p() 方法的基本語法:

math.log1p(x)

引數

此方法接受整數或浮點數作為引數,您需要計算 1 加上 x 的自然對數。

返回值

該方法返回 1 加上 x 的自然對數。返回值為浮點數。

示例 1

在下面的示例中,我們計算 1 + 1 的自然對數,這意味著將正整數作為引數傳遞給 log1p() 方法:

import math
result = math.log1p(1)
print("The result obtained is:", result)  

輸出

獲得的輸出如下:

The result obtained is: 0.6931471805599453

示例 2

在這裡,我們將負整數作為引數傳遞給 log1p() 方法。我們計算 1 - 0.5 的自然對數:

import math
result = math.log1p(-0.5)
print("The result obtained is:", result)  

輸出

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

The result obtained is: -0.6931471805599453

示例 3

在此示例中,我們計算 1 + 1000 的自然對數,這是一個很大的數:

import math
result = math.log1p(1000)
print("The result obtained is:", result)  

輸出

我們得到如下所示的輸出:

The result obtained is: 6.90875477931522

示例 4

現在,我們使用變數“x”來儲存引數。然後我們計算 1 + x 的自然對數:

import math
x = 2
result = math.log1p(x)
print("The result obtained is:", result)  

輸出

產生的結果如下所示:

The result obtained is: 1.0986122886681096
python_maths.htm
廣告