'error message with exception in cross product
I'm trying to define a class Vector, in a way the cross-product of two vectors v1 and v2 results in a perpendicular unit vector v3, while such a product is zero, then it should turn back an exception message. I've set the code as follows:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __repr__(self):
return "Vector(" + str(self.x) + ", " + str(self.y) + ", " + str(self.z) + ")"
def cross(self, V):
return Vector(self.y * V.z - self.z * V.y,self.z * V.x - self.x * V.z,self.x * V.y - self.y * V.x)
def find_axis(v,w):
x = v.cross(w)
print(type(x))
if x==Vector(0,0,0):
return "error"
#raise Exception(" (ValueError)")return x
But when trying to run the product between vectors, which cross product would be supposed to be different from zero, like the following example:
v = Vector(1, 2, 3)
w = Vector(1, 2, 3)
And I get excalty:
v.cross(w)
Vector(0, 0, 0)
I cannot figure out which the error is, since in this case the code is supposed to return an error message. Can anyone please know what is up?
A second way I tried was
class Vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __repr__(self):
return "Vector(" + str(self.x) + ", " + str(self.y) + ", " + str(self.z) + ")"
def cross(self, V):
return Vector(self.y * V.z - self.z * V.y,self.z * V.x - self.x * V.z,self.x * V.y - self.y * V.x)
def __eq__(self, V):
if self.x == V.x and self.y == V.y and self.z == V.z:
raise ValueError("negative x")
but I got the same problem
Solution 1:[1]
The solution to this just required to invert in the exact order the if statement unde cross definition:
class Vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __repr__(self):
return "Vector(" + str(self.x) + ", " + str(self.y) + ", " + str(self.z) + ")"
def cross(self, V):
if self.x == V.x and self.y == V.y and self.z == V.z:
raise ValueError("The vector is parallel and not perpendicular")
else:
return Vector(self.y * V.z - self.z * V.y, self.z * V.x - self.x * V.z,self.x * V.y - self.y * V.x)
#1st case
v = Vector(1, 2, 3)
w = Vector(9, 2, 3)
print(v.cross(w))
#2nd Case
v = Vector(1, 2, 3)
w = Vector(1, 2, 3)
print(v.cross(w))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ma?y_statystyczny |
