Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
like image 686
reggaelizard Avatar asked Feb 04 '14 23:02

reggaelizard


People also ask

How is the two point formula used to find the equation?

If you know two points on a line, you can use them to write the equation of the line in slope-intercept form. The first step will be to use the points to find the slope of the line. This will give you the value of m that you can plug into y = mx + b. The second step will be to find the y-intercept.

What is the equation of a line between two points?

The equation of a line passing through two points (x1, y1) and (x2, y2) is y - y1 = [y2−y1x2−x1](x - x1).


4 Answers

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 ...

like image 133
Joran Beasley Avatar answered Oct 29 '22 10:10

Joran Beasley


Let's assume that we have the following points:

P0: ( x0 = 100, y0 = 240 )

P1: ( x1 = 400, y1 = 265 )

We can compute the coefficients of the line y = a*x + b that connects the two points using the polyfit method from numpy.

import numpy as np
import matplotlib.pyplot as plt

# Define the known points
x = [100, 400]
y = [240, 265]

# Calculate the coefficients. This line answers the initial question. 
coefficients = np.polyfit(x, y, 1)

# Print the findings
print 'a =', coefficients[0]
print 'b =', coefficients[1]

# Let's compute the values of the line...
polynomial = np.poly1d(coefficients)
x_axis = np.linspace(0,500,100)
y_axis = polynomial(x_axis)

# ...and plot the points and the line
plt.plot(x_axis, y_axis)
plt.plot( x[0], y[0], 'go' )
plt.plot( x[1], y[1], 'go' )
plt.grid('on')
plt.show()

a = 0.0833333333333

b = 231.666666667

enter image description here


For installing numpy: http://docs.scipy.org/doc/numpy/user/install.html

like image 32
funk Avatar answered Oct 29 '22 11:10

funk


I think you are making pretty advanced code, but you are making it complicated. Here is a function that can do that:

from decimal import Decimal


def lin_equ(l1, l2):
    """Line encoded as l=(x,y)."""
    m = Decimal((l2[1] - l1[1])) / Decimal(l2[0] - l1[0])
    c = (l2[1] - (m * l2[0]))
    return m, c

# Example Usage:
lin_equ((-40, 30,), (20, 45))

# Result: (Decimal('0.25'), Decimal('40.00'))
like image 41
ironmann350 Avatar answered Oct 29 '22 09:10

ironmann350


I cleaned it up a bit; see what you think.

def slope(dx, dy):
    return (dy / dx) if dx else None

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
        return '({}, {})'.format(self.x, self.y)

    def __repr__(self):
        return 'Point({}, {})'.format(self.x, 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):
        dx = target.x - self.x
        dy = target.y - self.y
        return (dx*dx + dy*dy) ** 0.5

    def reflect_x(self):
        return Point(-self.x,self.y)

    def reflect_y(self):
        return Point(self.x,-self.y)

    def reflect_x_y(self):
        return Point(-self.x, -self.y)

    def slope_from_origin(self):
        return slope(self.x, self.y)

    def slope(self, target):
        return slope(target.x - self.x, target.y - self.y)

    def y_int(self, target):       # <= here's the magic
        return self.y - self.slope(target)*self.x

    def line_equation(self, target):
        slope = self.slope(target)

        y_int = self.y_int(target)
        if y_int < 0:
            y_int = -y_int
            sign = '-'
        else:
            sign = '+'

        return 'y = {}x {} {}'.format(slope, sign, y_int)

    def line_function(self, target):
        slope = self.slope(target)
        y_int = self.y_int(target)
        def fn(x):
            return slope*x + y_int
        return fn

and here are some use examples:

a = Point(2., 2.)
b = Point(4., 3.)

print(a)                   # => (2.0, 2.0)
print(repr(b))             # => Point(4.0, 3.0)
print(a.halfway(b))        # => (3.0, 2.5)

print(a.slope(b))          # => 0.5
print(a.y_int(b))          # => 1.0
print(a.line_equation(b))  # => y = 0.5x + 1.0

line = a.line_function(b)
print(line(x=6.))          # => 4.0
like image 4
Hugh Bothwell Avatar answered Oct 29 '22 09:10

Hugh Bothwell