Python complex() 函数用于通过组合实部和虚部来创建复数。
复数的实部表示位于标准数线(水平轴)上的分量。它是一个常规的实数,可以是正数、负数或零。在数学符号中,如果 “z” 是一个复数,则实部表示为 “Re(z)”。
复数的虚部表示位于虚轴(纵轴)上的分量。它是虚数单位 “i” (或 Python 中的 j) 的倍数,其中 “i” 定义为 “-1” 的平方根。在数学表示法中,如果 “z” 是一个复数,则虚部表示为 “Im(z)”。
语法
以下是 Python complex() 函数的语法 -
complex(real [,imag])
参数
此函数采用两个可选参数,如下所示 -
- real −它表示复数的实部。如果未提供,则默认为 0。
- imag (optional) −它表示复数的虚部。如果未提供,则默认为 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。
在这里,我们使用 complex() 函数,其中仅包含实部 “4” -
real = 4
result = complex(real)
print('The complex value obtained is:',result)
输出
上述代码的输出如下 -
The complex value obtained is: (4+0j)
示例 3
如果我们不将实部传递给 complex() 函数,则其默认值设置为 0。在这里,我们使用的是 complex() 函数,其中只有虚部 “7” -
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)