请帮忙 :/。如何在python中创建Complex Class,它执行与复数相关的所有函数,如(加,减,乘,除等)。此外,其他功能,如电源,规范等。
干得好!
来自copy import * from math import sqrt
类复杂:
def __init__(self, re, im):
self.re = deepcopy(re)
self.im = deepcopy(im)
def __str__(self):
r1 = self.re
i1 = self.im
if(r1 > 0 and i1 > 0):
r1 = str(r1)
r1 +='+'
if(abs(i1) != 1):
i1 = str(i1)
i1 += 'i'
else:
i1 = 'i'
elif(r1 == 0 and i1 == 0):
return '0'
elif(r1 <= 0 and i1<0):
if(r1 == 0):
r1 = str(r1)
r1 = ''
if(i1 == -1):
i1 = str(i1)
i1 = '-i'
else:
i1 = str(i1)
i1 += 'i'
elif(r1 <= 0 and i1>0):
if(r1 == 0):
r1 = str(r1)
r1 = ''
else:
r1 = str(r1)
r1 += '+'
if(i1 == 1):
i1 = str(i1)
i1 = 'i'
else:
i1 = str(i1)
i1 += 'i'
elif(r1 > 0 and i1 < 0):
i1 = self.im
i1 = str(i1)
if(i1 != '-1'):
i1 += 'i'
else:
i1 = '-i'
if(i1 == 0):
i1 = ''
self.__repr__()
ans = str(r1) + str(i1)
return ans
def __add__(self, other):
r1 = self.re + other.re
i1 = self.im + other.im
ans = Complex(r1,i1)
return ans
def __sub__(self, other):
r1 = self.re - other.re
i1 = self.im - other.im
ans = Complex(r1,i1)
return ans
def __mul__(self, other):
r1 = self.re * other.re
r2 = self.im * other.im
ex1 = r1 - r2
i1 = self.re * other.im
i2 = self.im * other.re
ex2 = i1 + i2
c = Complex(ex1,ex2)
return c
def __truediv__(self, other):
r1 = self.re * other.re
r2 = self.im * other.im
denom = other.re**2 + other.im**2
ex1 = int((r1 + r2) / denom)
i1 = self.re * other.im * (-1)
i2 = self.im * other.re
ex2 = int((i1 + i2) / denom)
c = Complex(ex1, ex2)
return c
def __eq__(self,other):
if(self.re==other.re and self.im==other.im):
return True
else:
return False
def norm(self):
r1 = self.re
i1 = self.im
p1 = r1*r1
p2 = i1*i1
c = p1 + p2
ans = int(sqrt(c))
return ans
def cpow(c,n):
r = Complex(1,0)
for i in range(n):
r = r.__mul__(c)
return r
如果name =='main':
zero = Complex(0,0)
one = Complex(1,0)
iota = Complex(0,1)
minus_one = Complex(-1, 0)
minus_iota = Complex(0, -1)
c1 = Complex(1,1)
v = Complex(0,-1)
x = Complex(2, 3)
y = Complex(4, 5)
z = x + y
print(z)
print(x-y)
print(x*y)
print(x/y)
print(iota)
希望这有助于交配。