Moi, oon tässä toisen projektin tarpeeseen tehnyt vektorikirjastoa. Jos ei kiinosta keksiä pyörää uudelleen niin voi vapaasti kopioda:
TVector.py:
#tkok's vector class import math class TVector(object): #data be array def __init__(self,components = []): self.c = components #adding new dimension def append(self, a): self.c.append(a) #print self def __str__(self): return ("TVectori: "+str(self.c)) #self == compare def __eq__(self,compare): if type(self)==type(compare): truth = True l=0 if len(self) > len(compare): l=len(self) else: l=len(compare) for i in range(l): if self[i] != compare[i]: truth = False break if truth: return 1 return 0 #self !=,<> compare def __ne__(self,compare): if self == compare: return 0 return 1 #len(self) def __len__(self): return len(self.c) #= self[key] def __getitem__(self, key): if len(self.c) > key: return self.c[key] return 0 #self[key] = def __setitem__(self, key,v): self.c[key] = v # = self[i:j] def __getslice__(self,i,j): return self.c[i:j] # self[i:j]= def __setslice__(self,i,j,v): self.c[i:j] = v # = self + a def __add__(self,a): t=TVector([]) if len(self) >= len(a): t[0::] = self[0::] for i in range(len(a)): t[i] += a[i] else: t.c [0::] = a[0::] for i in range(len(self)): t[i] += self[i] return t # = self - a def __sub__(self,a): t=TVector([]) t[0::] = self[0::] for i in range(len(a)): t[i] -= a[i] if len(self) < len(a): for i in range(len(self),len(a),1): t.append(-a[i]) return t # self +=,-= c def __iadd__(self, a): self = self + a return self def __isub__(self, a): self = self - a return self #abs(self) def __abs__(self): t=TVector([]) for i in range(len(self)): if self[i] < 0: t.append(self[i] * -1) else: t.append(self[i]) return t # -self def __neg__(self): t=TVector([]) for i in range(len(self)): t.append(self[i] * -1) return t #=self*const def __mul__(self,a): t=TVector([]) for i in range(len(self)): t.append(self[i] * a) return t #=self.div(const) def div(self,a): t=TVector([]) for i in range(len(self)): t.append(self[i] / a) return t #lenght of vector,float, ||self||, self.l() def l(self): t = 0 for i in range(len(self)): t += self[i]*self[i] return math.sqrt(t) #dot product def dot(self,a): t = 0 for i in range(len(self)): t += self[i]*a[i] return t #unit vector def unit(self): return(self.div(self.l())) #cross product def cross(self,a): if len(a) <=3 and len(self) <= 3: return TVector([self[1]*a[2]-self[2]*a[1],self[2]*a[0]-self[0]*a[2],self[0]*a[1]-self[1]*a[0]]) print("cross product ERROR,",self,a) return None #count angle between self and a: self.angle(a) def angle(self,a): print(len(self.c),a.l()) if self.l() != 0 or a.l() != 0: angle=math.degrees( math.acos(self.dot(a)/(self.l()*a.l()))) return angle else: print("angle ERROR") return 0 #return copy of vector def copy(self): return self.__class__(self.c) if __name__ == "__main__": b=TVector([1,1]) c=TVector([]) a=TVector([2,0,0]) print(a==b) print(a,b) print(a.angle(b)) print(a,b)
Aihe on jo aika vanha, joten et voi enää vastata siihen.