Länge und Normalisierung hinzugefügt
This commit is contained in:
15
vector.py
15
vector.py
@@ -1,4 +1,5 @@
|
|||||||
# -*- coding: iso-8859-15 -*
|
# -*- coding: iso-8859-15 -*
|
||||||
|
from math import sqrt
|
||||||
|
|
||||||
class Vector(object):
|
class Vector(object):
|
||||||
def __init__(self, coordinates):
|
def __init__(self, coordinates):
|
||||||
@@ -40,6 +41,18 @@ class Vector(object):
|
|||||||
new_coordinates = [c*x for x in self.coordinates]
|
new_coordinates = [c*x for x in self.coordinates]
|
||||||
return Vector(new_coordinates)
|
return Vector(new_coordinates)
|
||||||
|
|
||||||
|
def magnitude(self):
|
||||||
|
#Länge
|
||||||
|
coordinates_squared = [x**2 for x in self.coordinates]
|
||||||
|
return sqrt(sum(coordinates_squared))
|
||||||
|
|
||||||
|
def normalized(self):
|
||||||
|
try:
|
||||||
|
magnitude = self.magnitude()
|
||||||
|
return self.times_scalar(1./magnitude)
|
||||||
|
except ZeroDivisonError:
|
||||||
|
raise Exception('Ein Null-Vektor kann nicht normalisiert werden')
|
||||||
|
|
||||||
# Tests
|
# Tests
|
||||||
|
|
||||||
vektor_1 = Vector([1,2,3])
|
vektor_1 = Vector([1,2,3])
|
||||||
@@ -56,3 +69,5 @@ print vektor_1.plus(vektor_2)
|
|||||||
print vektor_2.minus(vektor_3)
|
print vektor_2.minus(vektor_3)
|
||||||
|
|
||||||
print vektor_3.times_scalar(3)
|
print vektor_3.times_scalar(3)
|
||||||
|
|
||||||
|
print "Magnitude -- Länge ", vektor_3.magnitude()
|
||||||
Reference in New Issue
Block a user