gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:09:48 25 4
gpt4 key购买 nike

我有一个类 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com