Python Complex Number Attributes and Methods Example
Category Programming Technology
A complex number is composed of a real number and an imaginary number, represented as: x+yj
A complex number is a pair of ordered floating-point numbers (x, y), where x is the real part and y is the imaginary part.
Concepts of Complex Numbers in Python:
- An imaginary number cannot exist alone; it always forms a complex number with a real part of 0.0.
- A complex number consists of a real part and an imaginary part.
- The syntax for representing an imaginary number is:
real+imagej
- Both the real part and the imaginary part are floating-point numbers.
- The imaginary part must have the suffix j or J.
#coding=utf8 aa=123-12j print aa.real # output real part 123.0 print aa.imag # output imaginary part -12.0
Output result:
123.0
-12.0
Built-in Attributes of Complex Numbers:
Complex number objects have data attributes, which are the real part and the imaginary part of the complex number.
Complex numbers also have a conjugate method, which returns the conjugate of the complex number when called.
Complex number attributes: real (real part of the complex number), imag (imaginary part of the complex number), conjugate() (returns the conjugate of the complex number)
#coding=utf8
class Complex(object):
'''Create a static attribute to record the class version number'''
version=1.0
'''Create a complex number class for operations and initialization'''
def __init__(self,rel=15,img=15j):
self.realPart=rel
self.imagPart=img
#Create a complex number
def creatComplex(self):
return self.realPart+self.imagPart
#Get the imaginary part of the input number
def getImg(self):
#Convert the imaginary part to a string
img=str(self.imagPart)
#Slice the string to get the numeric part
img=img[:-1]
return float(img)
def test():
print "run test..........."
com=Complex()
Cplex= com.creatComplex()
if Cplex.imag==com.getImg():
print com.getImg()
else:
pass
if Cplex.real==com.realPart:
print com.realPart
else:
pass
#Original complex number
print "the original complex is :",Cplex
#Conjugate of the complex number
print "the conjugate complex is :",Cplex.conjugate()
if __name__=="__main__":
test()
>
Reference Document: https://blog.csdn.net/henni_719/article/details/56665254
** Click to Share Notes
-
-
-