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
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))
Related
I'm trying creating a 3D class Vector and I have prepared the following code:
class Vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
#return string 'Vector(x,y,z)'
def __repr__(self):
return ("Vector(x,y,z)")
# or alternatively
#def __str__(self):
#return str("Vector3({0.x},{0.y},{0.z})".format(self))
# v == w
def __eq__(self, other):
self.v = Vector(self.x,self.y,self.z)
other.w = Vector(other.x, other.y, other.z)
if self.v() == self.w():
return True
else:
return False
#def __eq__(self, other): # poly1 == poly2
# return (self - other).is_zero() # it works when the substraction is defined
# v != w
def __ne__(self, other):
self.v = Vector(self.x,self.y,self.z)
other.w = Vector(other.x, other.y, other.z)
if self.v() != self.w():
return True
else:
return False
#def __ne__(self, other): # poly1 != poly2
# return not self == other
# v + w
def __add__(self, other):
if other == 0:
return self
else:
return vector(self.x+other.x, self.y+other.y, self.z+other.z)
# v - w
def __sub__(self, other):
self.x -= other.x
self.y -= other.y
self.z -= other.z
# return the dot product (number)
def __mul__(self, other):
self.v = Vector(self.x + self.y + self.z)
self.w = Vector(other.x + other.y + other.z)
return Vector(self.x*other.x,self.y*other.y, self.z*other.z)
#cross product
def __pow__(self, other):
return Vector(self.y*other.z - self.z*other.y,
self.z*other.x - self.x*other.z,
self.z*other.y - self.y*other.x)
# the length of the vector
def length(self):
return len(self)
# we assume that vectors are immutable
def __hash__(self):
return hash((self.x, self.y, self.z))
However no one of the following assert tests seem to work:
import math
v = Vector(1, 2, 3)
w = Vector(2, -3, 2)
assert v != w
assert v + w == Vector(3, -1, 5)
assert v - w == Vector(-1, 5, 1)
assert v * w == 2
assert v.cross(w) == Vector(13, 4, -7)
If someone tries running the following assert code, some errors pop up but I am not able to figure out what the problem is. Moreover, if it is possible I would lie to ask for a possible way to return the hash, length and string representation. Thanks
I'm trying to solve the tasks (text below), but I have a problem with the second point, i.e. method in it that displays the length of the segment and the positions of the start and end points.-
I don't really know how to write it, Could someone look at the code and give some hints?
Define a Point class with x, y fields and a method displaying the
point's position (eg "point (2,3)").
Then create a class Segment that will inherit from the class point.
Create a method in it that displays the length of the segment and the
positions of the start and end points.
Then define the Triangle class which will contain 3 Points,
automatically determined 3 Sections (walls) of them and included a
method for displaying the surface area of the perimeter.
code:
from math import sqrt, hypot
class Point:
def __init__(self, x_init, y_init):
self.x = x_init
self.y = y_init
def __str__(self):
return "Point(%s,%s)"%(self.x, self.y)
class Segment(Point):
def distance(self): **!-probably a badly written method**
return ((self.x ** 2) + (self.y ** 2)) ** 0.5
def position(self, p): **!-probably a badly written method**
dx = self.x - p.X
dy = self.y - p.Y
return hypot(dx, dy)
class Triangle(Point):
def __init__(self, x, y, z):
Point.__init__(self, x, y)
self.z = z
def __str__(self):
return "Point(x %s ,y %s, z %s )" % (self.x, self.y, self.z)
def __area__(a, b, c):
s = (a + b + c) / 2
return (s * (s - a) * (s - b) * (s - c)) ** 0.5
def __perimeter__(a, b, c):
s = (a + b + c)
return s
Task 2 is just wrong. Segment needs to contain 2 points, so it can't inherit from Point. It should be:
class Segment:
def __init__(self, start, end):
self.start = start
self.end = end
def distance(self):
dist = ((self.start.x - self.end.x) ** 2 + (self.start.y - self.end.y) ** 2) ** 0.5
print(f"distance from {self.start} to {self.end} is {dist}"
I need to change the code in line # 39
I have approximately seen scripts that use with open ("file.txt", "r") as f: take data from a text document.
I have a list of "Point.txt"
g = Point(250,127)
g = Point(330,224)
g = Point(557,186)
g = Point(370,197)
g = Point(222,107)
Need to add a function so that the script takes data from the list of the document "Point.txt"
and the whole result was saved in one document "Save.txt"
class Point(object):
def __init__(self, _x, _y, _order = None): self.x, self.y, self.order = _x, _y, _order
def calc(self, top, bottom, other_x):
l = (top * inverse_mod(bottom)) % p
x3 = (l * l - self.x - other_x) % p
return Point(x3, (l * (self.x - x3) - self.y) % p)
def double(self):
if self == INFINITY: return INFINITY
return self.calc(3 * self.x * self.x, 2 * self.y, self.x)
def __add__(self, other):
if other == INFINITY: return self
if self == INFINITY: return other
if self.x == other.x:
if (self.y + other.y) % p == 0: return INFINITY
return self.double()
return self.calc(other.y - self.y, other.x - self.x, other.x)
def __mul__(self, e):
if self.order: e %= self.order
if e == 0 or self == INFINITY: return INFINITY
result, q = INFINITY, self
while e:
if e&1: result += q
e, q = e >> 1, q.double()
return result
def __str__(self):
if self == INFINITY: return "infinity"
return " %x %x" % (self.x, self.y)
def inverse_mod(a):
if a < 0 or a >= p: a = a % p
c, d, uc, vc, ud, vd = a, p, 1, 0, 0, 1
while c:
q, c, d = divmod(d, c) + (c,)
uc, vc, ud, vd = ud - q*uc, vd - q*vc, uc, vc
if ud > 0: return ud
return ud + p
p, INFINITY = 1693, Point(None, None)
g = Point(250,127)
wave = 78
result = ' ID: %x\n getID: %s' % (wave, g*wave)
f = open('Save.txt', 'a')
f.write(result)
f.close()
I have used regex to extract the parameters that you have to pass for Point creation :
import re
f = open('Save.txt', 'a')
with open('Point.txt', 'rb') as points_txt_file:
for line in points_txt_file:
found_points = re.search(r'Point\((\s*\d+\s*),(\s*\d+\s*)\)', f'{line}')
print(found_points.groups())
param1 = int(found_points.group(1))
param2 = int(found_points.group(2))
g = Point(param1, param2)
result = ' ID: %x\n getID: %s' % (wave, g*wave)
f.write(result)
f.close()
Remove your code from line #38 and use this code .
G'day! When I know the slope and y-intercept of a line, I need to calculate an x-value that is 1 unit out from the line.
For example, if pointA = (4,5), and I set a line going from it with 0 slope (and therefore 5 as the y-intercept), then the x value I want would be 5. If the slope were undefined (vertical), then the x value would be 4. And so on.
So far, I calculate x as x = m(point[0]+1)-b. This doesn't work so well for vertical lines, however.
This and this are similar, but I can't read C# for the first, and on the second one, I don't need to eliminate any possible points (yet).
This is kind of hitting a nail with a sledge hammer, but if you're going to be running into geometry problems often, I'd either write or find a Point/Vector class like
import math
class Vector():
def __init__(self, x=0.0, y=0.0, z=0.0):
self.x = x
self.y = y
self.z = z
def __add__(self, other):
self.x += other.x
self.y += other.y
self.z += other.z
return self
def __sub__(self, other):
self.x -= other.x
self.y -= other.y
self.z -= other.z
return self
def dot(self, other):
return self.x*other.x + self.y*other.y + self.z*other.z
def cross(self, other):
tempX = self.y*other.z - self.z*other.y
tempY = self.z*other.x - solf.x*other.z
tempZ = self.x*other.y - self.y*other.x
return Vector(tempX, tempY, tempZ)
def dist(self, other):
return math.sqrt((self.x-other.x)**2 + (self.y-other.y)**2 + (self.z-other.z)**2)
def unitVector(self):
mag = self.dist(Vector())
if mag != 0.0:
return Vector(self.x * 1.0/mag, self.y * 1.0/mag, self.z * 1.0/mag)
else:
return Vector()
def __repr__(self):
return str([self.x, self.y, self.z])
Then you can do all kinds of stuff like find the vector by subtracting two points
>>> a = Vector(4,5,0)
>>> b = Vector(5,6,0)
>>> b - a
[1, 1, 0]
Or adding an arbitrary unit vector to a point to find a new point (which is the answer to your original question)
>>> a = Vector(4,5,0)
>>> direction = Vector(10, 1, 0).unitVector()
>>> a + direction
[4.995037190209989, 5.099503719020999, 0.0]
You can add more utilities, like allowing Vector/Scalar operations for scaling, etc.
I have the following code embeded in a class.Whenever I run distToPoint it gives the error 'unsupported operand type(s) for -: 'NoneType' and 'float'' I don't know why it's returning with NoneType and how do I get the subtraction to work?
Both self and p are supposed to be pairs.
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
def distToPoint(self,p):
self.ax = self.x - p.x
self.ay = self.y - p.y
self.ac = math.sqrt(pow(self.ax,2)+pow(self.ay,2))
For sake of comparison,
import math
class Point(object):
def __init__(self, x, y):
self.x = x + 0.
self.y = y + 0.
def distToPoint(self, p):
dx = self.x - p.x
dy = self.y - p.y
return math.sqrt(dx*dx + dy*dy)
a = Point(0, 0)
b = Point(3, 4)
print a.distToPoint(b)
returns
5.0
You should check what value of p you are sending to the function, so that it has an x and y that are floats.
Old post (on second thought, I don't think you were trying to use distToPoint this way):
distToPoint doesn't return a value, this is probably the problem.