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
广告

© . All rights reserved.