当前位置: 首页 > 工具软件 > iMAG > 使用案例 >

Python 内建函数 - complex([real[, imag]])

涂羽
2023-12-01

Manual

Return a complex number with the value real + imag*1j or convert a string or number to a complex number. If the first parameter is a string, it will be interpreted as a complex number and the function must be called without a second parameter. The second parameter can never be a string. Each argument may be any numeric type (including complex). If imag is omitted, it defaults to zero and the constructor serves as a numeric conversion like int and float. If both arguments are omitted, returns 0j.

Note When converting from a string, the string must not contain whitespace around the central + or - operator. For example, complex('1+2j') is fine, but complex('1 + 2j') raises ValueError.

The complex type is described in Numeric Types — int, float, complex.

直译

以实部+虚部*1j形式返回一个复数,或将字符串或数字转化为复数。如果第一个参数是字符串,它将会被转化为复数,且函数的调用不能有第二个参数,第二个参数永远不能是字符串。每个参数可以使任意数值类型(包括复数)。如果缺省虚部,它默认为0,构造器会以整数或浮点数值进行对待。如果两个参数都缺省,则返回0j。

注意:当从一个字符串转化时,字符串在中间的‘+’或‘-’操作符周围不能包含空格。例如:复数complex('1+2j')可行,但complex('1 + 2j')则会引发ValueError。

复数类型详见数值类型—整数,浮点数和复数

实例

>>> complex(0)
0j
>>> complex(3, 5)
(3+5j)
>>> complex(2.25, 163.33)
(2.25+163.33j)
>>> complex('1+2j')
(1+2j)
>>> complex('1 + 2j')
Traceback (most recent call last):
  File "<pyshell#144>", line 1, in <module>
    complex('1 + 2j')
ValueError: complex() arg is a malformed string
>>> complex('1+2j', '6j')
Traceback (most recent call last):
  File "<pyshell#145>", line 1, in <module>
    complex('1+2j', '6j')
TypeError: complex() can't take second arg if first is a string

拓展阅读

数值类型—整数,浮点数和复数

 类似资料: