从seg的一端计算沿线段的一个单位的点

时间:2015-05-19 15:00:04

标签: python python-2.7 geometry line point

天儿真好!当我知道一条线的斜率和y轴截距时,我需要计算一个距离线1个单位的x值。 例如,如果pointA =(4,5),并且我设置了一条从0开始的线,并且因此将0作为y轴截距,那么我想要的x值将是5.如果斜率未定义(垂直),那么x值将是4.依此类推。

到目前为止,我将x计算为x = m(point[0]+1)-b。然而,对于垂直线,这不是很好。 Thisthis相似,但我不能读第一个C#,而第二个,我不需要消除任何可能的点(还)。

1 个答案:

答案 0 :(得分:1)

这有点用大锤击打钉子,但是如果你经常遇到几何问题,我会写或找到一个Point / Vector类,如

import math
class Vector():
    def __init__(self, x=0.0, y=0.0, z=0.0):
        self.x = x
        self.y = y
        self.z = z

    def __add__(self, other):
        self.x += other.x
        self.y += other.y
        self.z += other.z
        return self

    def __sub__(self, other):
        self.x -= other.x
        self.y -= other.y
        self.z -= other.z
        return self

    def dot(self, other):
        return self.x*other.x + self.y*other.y + self.z*other.z

    def cross(self, other):
        tempX = self.y*other.z - self.z*other.y
        tempY = self.z*other.x - solf.x*other.z
        tempZ = self.x*other.y - self.y*other.x
        return Vector(tempX, tempY, tempZ)

    def dist(self, other):
        return math.sqrt((self.x-other.x)**2 + (self.y-other.y)**2 + (self.z-other.z)**2)

    def unitVector(self):
        mag = self.dist(Vector())
        if mag != 0.0:
            return Vector(self.x * 1.0/mag, self.y * 1.0/mag, self.z * 1.0/mag)
        else:
            return Vector()

    def __repr__(self):
        return str([self.x, self.y, self.z])

然后你可以做各种各样的事情,比如通过减去两点找到矢量

>>> a = Vector(4,5,0)
>>> b = Vector(5,6,0)
>>> b - a
[1, 1, 0]

或者向点添加任意单位矢量以找到新点(这是原始问题的答案)

>>> a = Vector(4,5,0)
>>> direction = Vector(10, 1, 0).unitVector()
>>> a + direction
[4.995037190209989, 5.099503719020999, 0.0]

您可以添加更多实用程序,例如允许使用矢量/标量操作进行缩放等。