from numpy.lib.scimath import sqrt class V2D: #costruttore def __init__(self,x,y): self.x=x self.y=y #conversione a stringa def __str__(self): return '({0},{1})'.format(self.x , self.y) #modulo def __abs__(self): #return sqrt(self.x**2+self.y**2) return sqrt(self*self) #uguaglianza v1==v2 def __eq__(self,other): tol=1e-6 return (abs(self.x - other.x) < tol) and (abs(self.y - other.y) < tol) #disuguaglianza def __ne__(self,other): return not self.__eq(other) #somma vettoriale def __add__(self,other): return V2D(self.x + other.x , self.y + other.y) #sottrazione vettoriale def __sub__(self,other): return V2D(self.x - other.x , self.y - other.y) #prodotto scalare def __mul__(self,other): return (self.x * other.x + self.y * other.y) if __name__=='__main__': #il costruttore accetta due parametri k=V2D(20,30) # V2D.__init__(k,20,30) v=V2D(2,3) #si definisce come ciascun vettore e' stampato print('k = ',k) print('v = ',v) #si definisce l'operatore di somma print('{0} + {1} = {2}'.format(k,v,k+v)) #sottrazione print('{0} - {1} = {2}'.format(k,v,k-v)) #moltiplicazione print('{0} * {1} = {2}'.format(k,v,k*v)) #valore assoluto print('abs(v) ',abs(v)) #uguaglianza print('v==k ',v==k) print('v==v ',v==v) #implementare anche un semplice sistema per gestire la tolleranza #nei test di uguaglianza print('-'*40) v2=V2D(2.0001,3.0001) v3=V2D(2.00000001,3.00000001) print('v = ',v) print('v2 = ',v2) print('v3 = ',v3) print('v==v2 ',v==v2) print('v==v3 ',v==v3)