1. Mètodes especials
1.1. Exercici 5.1
Atenció: falta el mètode producte vectorial associat a **
1 from math import sqrt
2
3 class Vector3d(object):
4 """
5 >>> from math import sqrt
6 >>> v1 = Vector3d (1, 1, 1)
7 >>> v2 = Vector3d (2, 3, 4)
8 >>> v3 = Vector3d (5, 2, 1)
9 >>> v1 + v2
10 (3, 4, 5)
11 >>> v1 - v2
12 (1, 1, 1)
13 >>> v2 * v3
14 (10, 6, 4)
15 >>> v1 * 2
16 (2, 2, 2)
17 >>> v1.modul() == sqrt(3)
18 True
19 """
20 def __init__(self, x, y, z):
21 self.x=x
22 self.y=y
23 self.z=z
24
25 def __add__(self, v):
26 self.x+=v.x
27 self.y+=v.y
28 self.z+=v.z
29 return (self.x, self.y, self.z)
30
31 def __sub__(self, v):
32 self.x-=v.x
33 self.y-=v.y
34 self.z-=v.z
35 return (self.x, self.y, self.z)
36
37 def __mul__(self, v):
38 if isinstance (v, Vector3d):
39 self.x=self.x*v.x
40 self.y=self.y*v.y
41 self.z=self.z*v.z
42 else:
43 self.x=self.x*v
44 self.y=self.y*v
45 self.z=self.z*v
46 return (self.x, self.y, self.z)
47
48 #falta el mètode producte vectorial associat a **
49
50 def modul(self):
51 mod = sqrt((self.x* self.x)+(self.y* self.y)+(self.z* self.z))
52 return mod
53
54 def cos_angle(self, v):
55 return (self*v)/(self.modul()*v.modul())