Python - AI 助手

Python cmath.isfinite() 函式



Python 的 cmath.isfinite() 函式用於檢查數字是否為有限數。

如果指定的數字是有限數,則此函式返回 True;否則,返回 False。在此函式中,如果浮點數為正數或負數,則認為它是有限數。

例如,如果我們有一個浮點數 (x= 3.14),則此函式將返回 True,因為 x 是一個有限數。

語法

以下是 Python cmath.isfinite() 函式的基本語法:

cmath.isfinite(x)

引數

此函式檢查給定的數字是否為有限數,它也接受一個數值作為引數。

返回值

此函式返回一個布林值,即 True 或 False。

示例 1

在以下示例中,我們使用 cmath.isfinite() 函式檢查給定複數的布林值。

import cmath
x = cmath.isfinite(10+3j)
print(x)

輸出

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

True

示例 2

在這裡,我們使用 cmath.isfinite() 函式檢查無窮大是否為有限浮點數。

import cmath
x = cmath.isfinite(float('inf'))
print(x)

輸出

獲得的輸出如下:

False

示例 3

現在,我們使用 cmath.isfinite 函式檢查 '0' 是否為有限數。

import cmath
result = cmath.isfinite(0)
print("The result is:", result)

輸出

我們將獲得以下輸出:

The result is: True

示例 4

在下面的示例中,如果給定的值不是數字,則此 cmath.isfinite 函式將返回 TypeError。

import cmath
res = cmath.isfinite("Welcome to Tutorialspoint")
print(res)

輸出

產生的結果如下所示:

Traceback (most recent call last):
  File "/home/cg/root/27484/main.py", line 2, in 
    res = cmath.isfinite("Welcome to Tutorialspoint")
TypeError: must be real number, not str

示例 5

在此示例中,我們使用 cmath.isfinite() 函式檢查 NaN(非數字)是否為有限浮點數。

import cmath
res = cmath.isfinite(float('NaN'))
print(res)

輸出

我們將獲得如下所示的輸出:

False
python_modules.htm
廣告