Python complex() 函式



Python 的 complex() 函式用於透過組合實部和虛部來建立一個複數。

複數的實部表示位於標準數軸(水平軸)上的分量。它是一個普通的實數,可以是正數、負數或零。在數學符號中,如果“z”是一個複數,則實部表示為“Re(z)”。

複數的虛部表示位於虛軸(垂直軸)上的分量。它是虛數單位“i”(或 Python 中的“j”)的倍數,其中“i”定義為“-1”的平方根。在數學符號中,如果“z”是一個複數,則虛部表示為“Im(z)”。

語法

以下是 Python complex() 函式的語法:

complex(real [,imag])

引數

此函式採用兩個可選引數,如下所示:

  • real - 它表示複數的實部。如果未提供,則預設為 0。

  • imag(可選) - 它表示複數的虛部。如果未提供,則預設為 0。

返回值

此函式根據提供的實部和虛部返回一個複數,或者返回一個表示複數的字串。

示例 1

在以下示例中,我們使用 complex() 函式建立一個實部為“2”、虛部為“3”的複數:

real = 2
imaginary = 3
result = complex(real, imaginary)
print('The complex value obtained is:',result)

輸出

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

The complex value obtained is: (2+3j)

示例 2

如果我們不向 complex() 函式傳遞虛部,則其預設值為 0。

在這裡,我們僅使用實部“4”來呼叫 complex() 函式:

real = 4
result = complex(real)
print('The complex value obtained is:',result)

輸出

上述程式碼的輸出如下:

The complex value obtained is: (4+0j)

示例 3

如果我們不向 complex() 函式傳遞實部,則其預設值為 0。在這裡,我們僅使用虛部“7”來呼叫 complex() 函式:

imaginary = 7
result = complex(imag=imaginary)
print('The complex value obtained is:',result)

輸出

獲得的結果如下所示:

The complex value obtained is: (7+0j)

示例 4

在這裡,我們使用 complex() 函式,既不提供實部也不提供虛部。因此,它預設為 0j,表示一個實部和虛部都等於 0 的複數:

result = complex()
print('The complex value obtained is:',result)

輸出

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

The complex value obtained is: 0j

示例 5

在下面的示例中,complex() 函式解析字串“2+4j”並建立相應的複數 (2+4j):

result = complex("2+4j")
print('The complex value obtained is:',result)

輸出

產生的結果如下所示:

The complex value obtained is: (2+4j)
python_type_casting.htm
廣告