【问题标题】:Method to return the equation of a straight line given two points返回给定两点的直线方程的方法
【发布时间】:2014-03-01 05:16:17
【问题描述】:

我有一个类Point,由一个带有x和y坐标的点组成,我必须编写一个方法来计算并返回连接Point对象和另一个Point对象的直线方程这是作为参数传递的(my_point.get_straight_line(my_point2)。我知道如何在纸上用 yy1 = m(xx1) 计算它,我已经有一个方法 @987654325 @ 计算 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

感谢任何帮助。

编辑:我用一个计算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)

【问题讨论】:

  • 你所拥有的看起来不错。你到底有什么问题?
  • 我真的无法弄清楚self.x、self.y、target.x 和target.y 中的哪些值将是等式中的每个值,以及如何制定它以便计算 c。
  • self.x 是 x,target.x 是 x1。或相反亦然。谁在乎!只要你以一种或另一种方式保持一致。

标签: python python-3.x


【解决方案1】:
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))

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

【讨论】:

  • 这正是我要寻找的。​​span>
  • 你能把这个例子编辑成对 python 3 友好吗? IE。括号
  • 使用最小二乘法来求解一个数学上可解的方程只有一个解,这不是矫枉过正吗?
【解决方案2】:

我清理了一下;看看你的想法。

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

以下是一些使用示例:

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

【讨论】:

  • 它看起来不错,但我想解释一下每个部分的确切作用以及为什么它很重要,以及 .format() 方法是如何工作的,因为我以前从未见过它。抱歉,如果我问的是令人尴尬的愚蠢问题,在开始使用 Python 之前我从未真正做过任何编程!
  • @reggaelizard 有时最好自己查找文档,查看this。
【解决方案3】:

假设我们有以下几点:

P0: (x0 = 100, y0 = 240)

P1: (x1 = 400, y1 = 265)

我们可以使用 numpy 中的 polyfit 方法计算连接两点的线 y = a*x + b 的系数。

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


用于安装 numpy:http://docs.scipy.org/doc/numpy/user/install.html

【讨论】:

    【解决方案4】:

    我认为您正在编写非常高级的代码,但您正在使它变得复杂。这是一个可以做到这一点的函数:

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

    【讨论】:

    • 十进制模块除了保证浮点类型外,还能为你做什么?
    • @Sledge : 甚至可以通过使用内置的float()
    • 可以抛出 DivisionByZero
    【解决方案5】:
    class Line(object):
    
        def __init__(self,coor1,coor2):
            self.coor1 = coor1
            self.coor2 = coor2
    
    
        def distance(self):
            x1,y1 = self.coor1
            x2,y2 = self.coor2
            return ((x2-x1)**2+(y2-y1)**2)**0.5    
    
        def slope(self):
            x1,x2 = self.coor1
            y1,y2 = self.coor2
            return (float(y2-y1))/(x2-x1)
    

    【讨论】:

      【解决方案6】:
      l=[1,1,2,2]
      #l=[x1,y1,x2,y2]
      y0=l[3]-l[1]
      x0=l[0]-l[2]
      c = l[1]*l[2]-l[0]*l[3]
      if(x0>0):
          print(y0,"x","+",x0,"y=",c)
      else:
          print(y0,"x",x0,"y=",c)
      

      【讨论】:

        猜你喜欢
        • 2011-03-03
        • 1970-01-01
        • 2023-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-11
        相关资源
        最近更新 更多