你怎么能确定一个点在线段上的其他两点之间? [英] How can you determine a point is between two other points on a line segment?

查看:113
本文介绍了你怎么能确定一个点在线段上的其他两点之间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你有一个二维平面,其上有2个点(称为a和b),每个点用一个x整数和一个整数表示。

你能确定另一个点c是否位于由a和b定义的线段上吗?



我最常使用python,但任何语言的示例都会有帮助。 >

解决方案

检查(ba)和(ca)的跨产品是否为0,告诉你a,b和c点是否对齐。



但是,如果你想知道c是在a和b之间,你还必须检查(ba)和(ca)的点积

在非优化伪代码中:

  def isBetween(a,b,c ):
crossproduct =(cy - ay)*(bx - ax) - (cx - ax)*(by - ay)

#与浮点数val的epsilon比较ues或!= 0如果使用整数
if abs(crossproduct)> epsilon:
return False

dotproduct =(c.x - a.x)*(b.x - a.x)+(c.y - a.y)*(b.y - a.y)
if dotproduct< 0:
return False

squaredlengthba =(b.x - a.x)*(b.x - a.x)+(b.y - a.y)*(b.y - a.y)
if dotproduct> squaredlengthba:
返回False

返回True


Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.

How can you determine if another point c is on the line segment defined by a and b?

I use python most, but examples in any language would be helpful.

解决方案

Check if the cross product of (b-a) and (c-a) is 0, as tells Darius Bacon, tells you if the points a, b and c are aligned.

But, as you want to know if c is between a and b, you also have to check that the dot product of (b-a) and (c-a) is positive and is less than the square of the distance between a and b.

In non-optimized pseudocode:

def isBetween(a, b, c):
    crossproduct = (c.y - a.y) * (b.x - a.x) - (c.x - a.x) * (b.y - a.y)

    # compare versus epsilon for floating point values, or != 0 if using integers
    if abs(crossproduct) > epsilon:
        return False

    dotproduct = (c.x - a.x) * (b.x - a.x) + (c.y - a.y)*(b.y - a.y)
    if dotproduct < 0:
        return False

    squaredlengthba = (b.x - a.x)*(b.x - a.x) + (b.y - a.y)*(b.y - a.y)
    if dotproduct > squaredlengthba:
        return False

    return True

这篇关于你怎么能确定一个点在线段上的其他两点之间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆