Method to return the equation of a straight line given two points

python, python-3.x

Solution

from numpy import ones,vstack
from numpy.linalg import lstsq
points = [(1,5),(3,4)]
x_coords, y_coords = zip(*points)
A = vstack([x_coords,ones(len(x_coords))]).T
m, c = lstsq(A, y_coords)[0]
print("Line Solution is y = {m}x + {c}".format(m=m,c=c))

but really your method should be fine ...

Problem

I have a class `Point`, consisting of a point with x and y coordinates, and I have to write a method that computes and returns the equation of a straight line joining a `Point` object and another `Point` object that is passed as an argument (`my_point.get_straight_line(my_point2)`. I know how to calculate that on paper with y-y1 = m(x-x1) and I already have a method `my_point.slope(my_point2)` to compute `m`, but I can't really wrap my head around how to translate the equation to Python. Here's the entire class: ``` class Point: def __init__(self,initx,inity): self.x = initx self.y = inity def getx(self): return self.x def gety(self): return self.y def negx(self): return -(self.x) def negy(self): return -(self.y) def __str__(self): return 'x=' + str(self.x) + ', y=' + str(self.y) def halfway(self,target): midx = (self.x + target.x) / 2 midy = (self.y + target.y) / 2 return Point(midx, midy) def distance(self,target): xdiff = target.x - self.x ydiff = target.y - self.y dist = math.sqrt(xdiff**2 + ydiff**2) return dist def reflect_x(self): return Point(self.negx(),self.y) def reflect_y(self): return Point(self.x,self.negy()) def reflect_x_y(self): return Point(self.negx(),self.negy()) def slope_from_origin(self): if self.x == 0: return None else: return self.y / self.x def slope(self,target): if target.x == self.x: return None else: m = (target.y - self.y) / (target.x - self.x) return m ``` Any help is appreciated. EDIT: I figured it out with an equation that computes `c` and then just returns it in a string along with `self.slope(target)`! This turned out to be way less complicated than I thought. ``` def get_line_to(self,target): c = -(self.slope(target)*self.x - self.y) return 'y = ' + str(self.slope(target)) + 'x + ' + str(c) ```

Original source