from numpy.lib.scimath import sqrt class V2D: #######GESTIONE-TOLLERANZA####### #membro statico della classe __tol=1e-6 #metodo della classe @classmethod #senza questo cls si riferirebbe all'oggetto e non alla classe (come self) def set_tol(cls,t): cls.__tol = t @classmethod#senza questo cls si riferirebbe all'oggetto e non alla classe (come self) def get_tol(cls): return cls.__tol #######METODI####### #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) #uguaglianza def __eq__(self,other): return (abs(self.x - other.x) < V2D.get_tol()) and (abs(self.y - other.y) < V2D.get_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__': k=V2D(20,30) v=V2D(2,3) print('{0} + {1} = {2}'.format(k,v,k+v)) print('{0} - {1} = {2}'.format(k,v,k-v)) print('{0} * {1} = {2}'.format(k,v,k*v)) print('abs(v) ',abs(v)) print('v==k ',v==k) print('v==v ',v==v) print('-'*40) V2D.set_tol(1e-2) print('tolleranza = {0}'.format(V2D.get_tol())) v2=V2D(2.0001,3.0001) v3=V2D(2.00000001,3.00000001) print('v==v2 ',v==v2) print('v==v3 ',v==v3) print('-'*40) V2D.set_tol(1e-5) print('tolleranza = {0}'.format(V2D.get_tol())) v2=V2D(2.0001,3.0001) v3=V2D(2.00000001,3.00000001) print('v==v2 ',v==v2) print('v==v3 ',v==v3) print('-'*40) V2D.set_tol(1e-10) print('tolleranza = {0}'.format(V2D.get_tol())) v2=V2D(2.0001,3.0001) v3=V2D(2.00000001,3.00000001) print('v==v2 ',v==v2) print('v==v3 ',v==v3)