标签归档:complex-numbers

python中的复数用法

问题:python中的复数用法

我是数学新手。现在,我将更深入地了解Python数据类型。我不明白如何使用复数。请给我示例在Python中使用复数的示例。

I’m a math newbie. Now I’m getting deeper into Python data types. I can’t understand how to use a complex number. Please give me examples of usage of complex numbers in Python.


回答 0

在python中,您可以在数字后面加上’j’或’J’以使其虚构,因此您可以轻松地编写复杂的文字:

>>> 1j
1j
>>> 1J
1j
>>> 1j * 1j
(-1+0j)

后缀“ j”来自电气工程,其中变量“ i”通常用于电流。(推理在这里找到。

复数的类型为complex,并且您可以根据需要将其用作构造函数:

>>> complex(2,3)
(2+3j)

复数具有一些内置访问器:

>>> z = 2+3j
>>> z.real
2.0
>>> z.imag
3.0
>>> z.conjugate()
(2-3j)

几个内置函数支持复数:

>>> abs(3 + 4j)
5.0
>>> pow(3 + 4j, 2)
(-7+24j)

标准模块cmath具有更多处理复数的功能:

>>> import cmath
>>> cmath.sin(2 + 3j)
(9.15449914691143-4.168906959966565j)

In python, you can put ‘j’ or ‘J’ after a number to make it imaginary, so you can write complex literals easily:

>>> 1j
1j
>>> 1J
1j
>>> 1j * 1j
(-1+0j)

The ‘j’ suffix comes from electrical engineering, where the variable ‘i’ is usually used for current. (Reasoning found here.)

The type of a complex number is complex, and you can use the type as a constructor if you prefer:

>>> complex(2,3)
(2+3j)

A complex number has some built-in accessors:

>>> z = 2+3j
>>> z.real
2.0
>>> z.imag
3.0
>>> z.conjugate()
(2-3j)

Several built-in functions support complex numbers:

>>> abs(3 + 4j)
5.0
>>> pow(3 + 4j, 2)
(-7+24j)

The standard module cmath has more functions that handle complex numbers:

>>> import cmath
>>> cmath.sin(2 + 3j)
(9.15449914691143-4.168906959966565j)

回答 1

下面的复数示例应易于说明,最后包括错误消息

>>> x=complex(1,2)
>>> print x
(1+2j)
>>> y=complex(3,4)
>>> print y
(3+4j)
>>> z=x+y
>>> print x
(1+2j)
>>> print z
(4+6j)
>>> z=x*y
>>> print z
(-5+10j)
>>> z=x/y
>>> print z
(0.44+0.08j)
>>> print x.conjugate()
(1-2j)
>>> print x.imag
2.0
>>> print x.real
1.0
>>> print x>y

Traceback (most recent call last):
  File "<pyshell#149>", line 1, in <module>
    print x>y
TypeError: no ordering relation is defined for complex numbers
>>> print x==y
False
>>> 

The following example for complex numbers should be self explanatory including the error message at the end

>>> x=complex(1,2)
>>> print x
(1+2j)
>>> y=complex(3,4)
>>> print y
(3+4j)
>>> z=x+y
>>> print x
(1+2j)
>>> print z
(4+6j)
>>> z=x*y
>>> print z
(-5+10j)
>>> z=x/y
>>> print z
(0.44+0.08j)
>>> print x.conjugate()
(1-2j)
>>> print x.imag
2.0
>>> print x.real
1.0
>>> print x>y

Traceback (most recent call last):
  File "<pyshell#149>", line 1, in <module>
    print x>y
TypeError: no ordering relation is defined for complex numbers
>>> print x==y
False
>>>