python - 返回给定两点的直线方程的方法

标签 python python-3.x

我有一个类 Point ,由一个具有 x 和 y 坐标的点组成,我必须编写一个方法来计算并返回连接 Point 对象和作为参数传递的另一个 Point 对象的直线方程( my_point.get_straight_line(my_point2) 。我知道如何在纸上用 y-y1 = m(x-x1) 计算,我已经有一个方法 my_point.slope(my_point2) 来计算 m ,但我不能我真的全神贯注于如何将等式转换为 Python。这是整个类(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

感谢任何帮助。

编辑: 我用计算 c 的方程式计算出来,然后将它与 self.slope(target) 一起返回到一个字符串中!事实证明这比我想象的要简单得多。

def get_line_to(self,target):
    c = -(self.slope(target)*self.x - self.y)
    return 'y = ' + str(self.slope(target)) + 'x + ' + str(c)

最佳答案

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

但实际上你的方法应该没问题......

关于python - 返回给定两点的直线方程的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21565994/

相关文章:

python - 避免模​​ block 名称修改的干净方法?

python - 使用 Python 组合正则表达式中的两个列表

Python:在 locals() 中查找键的类型

python - 从列表末尾删除零

python - 使用请求登录网站

Python 读取 Tick Data Pandas

python - 在 tensorflow 中,可训练梯度和停止梯度有什么区别

python - 架子写入空白列表/字典

python 3 : Exception or return code when resource limit exceeded?

python - 将Python库添加到远程集群机器?