Python - AI 助手

Python cmath.nan 常量



Python 的 cmath.nan 常量返回一個浮點型 NaN(非數字)。此常量表示為NaN。它是一個預定義的值,用於表示未定義的數值,實際上這些是由數學運算引發的。

NaN 用於表示數學上未定義的運算結果,例如零除以零,負數的平方根。

語法

以下是 Python cmath.nan 常量的基本語法:

cmath.nan

示例 1

在下面的示例中,我們正在建立一個 NaN 值。我們將初始化一個變數為 cmath.nan 常量,該常量指示數值資料。

import cmath
x = cmath.nan
print("The value of x is:", x)

輸出

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

The value of x is: nan

示例 2

現在,我們正在建立一個新的列表“valid_data”,其中只包含原始列表中非 NaN 的值。

import cmath
data = [4.6, cmath.nan, 7.7, cmath.nan, 2.9]
valid_data = [x for x in data if not cmath.isnan(x)]
print("The valid data points are:", valid_data)

輸出

獲得的結果如下:

The valid data points are: [4.6, 7.7, 2.9]

示例 3

在這裡,我們計算 NaN 數字的和(任何 NaN 數字的和始終為 NaN)。

import cmath
x = 10
y = cmath.nan
z = 20
w = cmath.nan
result = x + y + z +w
print("The result of the calculation is:", result)

輸出

輸出如下:

The result of the calculation is: nan

示例 4

現在,我們使用 cmath.nan 建立一個包含數值(包括 NaN 值)的列表。我們將比較列表中的所有值並過濾 NaN 值。

import cmath
values = [15, cmath.nan, 63, cmath.nan, 25]
filtered_values = [x for x in values if not cmath.isnan(x)]
print("The list after filtering out NaN values is:", filtered_values)

輸出

我們將得到如下輸出:

The list after filtering out NaN values is: [15, 63, 25]
python_modules.htm
廣告