From 7fc75fdde340327d3345680a4ac08ef326bab736 Mon Sep 17 00:00:00 2001 From: Sven Riwoldt Date: Fri, 6 Nov 2020 07:36:26 +0100 Subject: [PATCH] =?UTF-8?q?L=C3=A4nge=20und=20Normalisierung=20hinzugef?= =?UTF-8?q?=C3=BCgt?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- vector.py | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/vector.py b/vector.py index 95c2da4..7f0b96c 100644 --- a/vector.py +++ b/vector.py @@ -1,4 +1,5 @@ # -*- coding: iso-8859-15 -* +from math import sqrt class Vector(object): def __init__(self, coordinates): @@ -39,6 +40,18 @@ class Vector(object): def times_scalar(self, c): new_coordinates = [c*x for x in self.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 @@ -55,4 +68,6 @@ print vektor_1.plus(vektor_2) print vektor_2.minus(vektor_3) -print vektor_3.times_scalar(3) \ No newline at end of file +print vektor_3.times_scalar(3) + +print "Magnitude -- Länge ", vektor_3.magnitude() \ No newline at end of file