Python math.exp() 方法



Python 的 math.exp() 方法用於計算尤拉數 'e' 的數值次冪。

尤拉數簡單來說是一個數學表示式,通常用作自然對數的底數。它是一個無限不迴圈小數,其值為 2.718281828459045… 然而,在大多數問題中,這個數字通常簡化為小數點後兩位,即 2.71。

尤拉數主要用於處理指數函式(遞增或遞減)的問題。該數字用字母 e 表示。

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

語法

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

math.exp( x )

引數

  • x - 這是指數值。

返回值

此方法返回 x 的指數:ex

示例

以下示例演示了 Python math.exp() 方法的用法。在這裡,我們嘗試找到尤拉數在提高到正值時的指數值。

import math

# Create two number objects with one integer and one float
x = 3
y = 5.6

# Calculate the exponent for both numbers
exp1 = math.exp(x)
exp2 = math.exp(y)

# Display the return values
print("The exponent of x is", exp1)
print("The exponent of y is", exp2)

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

The exponent of x is 20.085536923187668
The exponent of y is 270.42640742615254

示例

尤拉數的數值次冪結果始終為正數,即使該數值為負數。

在以下示例中,我們建立了兩個包含負值的數值物件,並將它們作為引數傳遞給此方法。然後,該方法使用這些物件計算指數值並返回它們。

import math

# Create two number objects with one integer and one float
x = -5
y = -0.6

# Calculate the exponent for both numbers
exp1 = math.exp(x)
exp2 = math.exp(y)

# Display the return values
print("The exponent of x is", exp1)
print("The exponent of y is", exp2)

編譯並執行給定程式後,輸出將顯示如下:

The exponent of x is 0.006737946999085467
The exponent of y is 0.5488116360940265

示例

如果尤拉數提高到無效數字,結果也將是無效數字。

在這裡,我們建立一個包含 NaN 值的物件。在 Python 中,我們通常使用 float() 建立 NaN 值物件。然後將此物件作為引數傳遞給 exp() 方法,該方法計算其指數值。

import math

# Create a number objects with a float NaN value
x = float("nan")

# Calculate the exponent for NaN
exp = math.exp(x)

# Display the return values
print("The exponent of x is", exp)

讓我們編譯並執行上面的程式,以產生如下輸出:

The exponent of x is nan

示例

如果尤拉數提高到正無窮大或負無窮大,則返回值將分別為正無窮大和 0。

在此示例中,我們建立一個包含無窮大值的物件。在 Python 中,我們通常使用 float() 建立無窮大值物件。然後將此物件作為引數傳遞給 exp() 方法,該方法計算其指數值。

import math

# Create two number objects with float infinity values
x = float("INF")
y = float("-INF")

# Calculate the exponent for NaN
exp1 = math.exp(x)
exp2 = math.exp(y)

# Display the return values
print("The exponent of x is", exp1)
print("The exponent of y is", exp2)

The exponent of x is inf
The exponent of y is 0.0

示例

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

import math

# Create a string object
x = 'a'

# Calculate the exponent for x
exp = math.exp(x)

# Display the return values
print("The exponent of x is", exp)

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

Traceback (most recent call last):
  File "main.py", line 7, in 
exp = math.exp(x)
TypeError: must be real number, not str
python_maths.htm
廣告