python 复数基础

在python中复数的处理相对简单,定义一个复数通常来说有两种方式,代码如下:
NB(注意): # 后面的部分表示输出结果。

class Debug:
    def complexDefine(self):
        # method 1
        x = 1j
        print(x)			# 1j
        print(type(x))		# <class 'complex'>

		# method 2
        x1 = complex(1, 2)
        print(x1)			# (1+2j)
        print(type(x1))		# <class 'complex'>

# debug
main = Debug()
main.complexDefine()

我们可以看到可以直接使用j来创建一个虚数,也可以使用关键字complex来创建一个虚数,并且虚数同时拥有实部与虚部时,实部在前,虚部在后,如定义方法二中的(1+2j),其中1为实部,2为虚部。
此外在python还存在一个内置模块cmath可以用来处理复数运算,代码如下:

class Debug:
    def complexDefine(self):
		x = -1
        x1 = cmath.sqrt(x)
        print(x1)			# 1j

# debug
main = Debug()
main.complexDefine()

那么如何获取复数的实部和虚部呢?代码如下:

class Debug:
    @staticmethod
    def complexDefine():
        x = complex(1, 2)
        x_real = x.real
        x_image = x.imag
        print('The real part of this complex number is:')
        print(x_real)
        print('The imaginary part of this complex number is:')
        print(x_image)


main = Debug()
main.complexDefine()
"""
The real part of this complex number is:
1.0
The imaginary part of this complex number is:
2.0
"""

由此我们可以知道,可以通过.real.image来分别获取一个复数的实部与虚部部分。

码字不易,如果大家觉得有用,请高抬贵手给一个赞让我上推荐让更多的人看到吧~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

勤奋的大熊猫

你的鼓励将是我写作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值