我有一个类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 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
任何帮助都很感激。
- EDIT:**我用一个计算
c
的公式计算出来的,然后在一个字符串中返回它和self.slope(target)
!这比我想象的要简单得多。
- EDIT:**我用一个计算
def get_line_to(self,target):
c = -(self.slope(target)*self.x - self.y)
return 'y = ' + str(self.slope(target)) + 'x + ' + str(c)
6条答案
按热度按时间j2qf4p5b1#
但你的方法应该没问题。
0vvn1miw2#
让我们假设我们有以下几点:
P0:(x0 = 100,y0 = 240)
P1:(x 1 = 400,y 1 = 265)
我们可以使用numpy中的polyfit方法计算连接两点的直线y = a*x + B的系数。
a = 0.083333333333
B = 231.6666666667
对于安装numpy:http://docs.scipy.org/doc/numpy/user/install.html
lndjwyie3#
我认为你正在编写非常高级的代码,但是你使它变得复杂了。下面是一个函数可以做到这一点:
kx7yvsdv4#
我清理了一下;看看你怎么想。
下面是一些使用示例:
uqjltbpv5#
e0bqpujr6#