Python: Exemple de classe Complexe
Jump to navigation
Jump to search
class Complexe:
"""
Une classe toute simple de nombres complexes
"""
real = 0.0
imag = 0.0
def __init__(self,r=0.0,i=0.0,module=0.0,phase=0.0):
"Constructeur avec paramètres optionnels nommés"
#tentative de conversion en réel
self.real = float(r)
self.imag = float(i)
module = float(module)
phase = float(phase)
if module:
from math import cos,sin
self.real = module*cos(phase)
self.imag = module*sin(phase)
def __str__(self):
"affichage de l'objet avec le mot-cle print"
return str(self.real)+('+' if self.imag >=0.0 else '') \
+ str(self.imag)+'i'
def __add__(self,other):
"additionne deux complexes"
if not other.__class__ is Complexe:
print "Erreur: l'argument n'est pas un complexe"
return NotImplemented
return Complexe(self.real+other.real,self.imag+other.imag)
def __sub__(self,other):
"soustrait deux complexes"
if not other.__class__ is Complexe:
print "Erreur: l'argument n'est pas un complexe"
return NotImplemented
return Complexe(self.real-other.real,self.imag-other.imag)
def __mul__(self,other):
"multiplie deux complexes"
if other.__class__ is Complexe:
return Complexe(self.real*other.real - self.imag*other.imag, \
self.imag*other.real + self.real*other.imag)
elif other.__class__ is float or other.__class__ is int:
return Complexe(self.real*other,self.imag*other)
else:
print "Erreur: l'argument n'est pas du bon type"
return NotImplemented
def module2(self):
"retourne le module au carré"
return (self*self.conj()).real
def conj(self):
"renvoie le conjugué"
return Complexe(self.real,-self.imag)
def conj(c):
return c.conj()
def abs(c): # surcharge de la fonction abs
from math import sqrt
return sqrt(c.module2())
from math import pi
print Complexe(1,0),Complexe(0,1),Complexe(0,0),Complexe(1,1)
print Complexe(module=1.0,phase=pi/2)
a = Complexe(1,-1.432)
print a, conj(a), a.module2(), abs(a)
print a + a, a - a
print a*3 # attention le second argument doit être à droite
print Complexe(3.0)*a