如何编写一个C程序来检查一个点是否位于一个正方形内,给定一个对角线

时间:2017-02-23 04:37:54

标签: c algorithm math

我正在解决上面提到的问题但是对数学方程和变量太过困惑了。我开始尝试找到另外两个点的坐标但是方程式无法由我解决,存在很多变量并且我感到困惑。如果这已经完成,我会尝试检查关于两侧的点的位置,但这也包括很多变量和混乱。一个好的算法可能会有所帮助。 谢谢!

3 个答案:

答案 0 :(得分:4)

让顶点为A和B,点为P(图中意外命名为C)。查找向量AB,AP,BP

enter image description here

AB.X = B.X - A.X
AB.Y = B.Y - A.Y
and so on
如果点积是非负的

,则p位于正方形内
cA = AP x AB    //(AP.X * AB.Y - AP.Y * AB.X)
dA = AP dot AB   //(AP.X * AB.X + AP.Y * AB.Y)
cB = -(AB x BP)
dB = -(AB dot BP)

和交叉产品的绝对值小于点积

dA >= Abs(cA)
dB >= Abs(cB)

(这相当于检查角度是否在范围-Pi/4..Pi/4

答案 1 :(得分:3)

你可以找到剩下的两个方块:

x1 = ?  ;  y1 = ? ;    // First diagonal point
x2 = ?  ;  y2 = ? ;    // Second diagonal point

xc = (x1 + x2)/2  ;  yc = (y1 + y2)/2  ;    // Center point
xd = (x1 - x2)/2  ;  yd = (y1 - y2)/2  ;    // Half-diagonal

x3 = xc - yd  ;  y3 = yc + xd;    // Third corner
x4 = xc + yd  ;  y4 = yc - xd;    // Fourth corner

在有四个正方形点后,您可以检查给定点是否位于正方形内,然后四个三角形的面积如下图所示将等于正方形面积。 enter image description here

了解更多:

https://math.stackexchange.com/questions/506785/given-two-diagonally-opposite-points-on-a-square-how-to-calculate-the-other-two

https://martin-thoma.com/how-to-check-if-a-point-is-inside-a-rectangle/

答案 2 :(得分:2)

假设您的问题是 2D (如 3D N-D ,您需要更多信息)。我会这样解决:

  1. 找到2个缺少的顶点

    所以我们知道from datetime import date from random import randint from bokeh.models import AjaxDataSource from bokeh.models.widgets import DataTable, DateFormatter, TableColumn from bokeh.models.layouts import WidgetBox from bokeh.plotting import show source=AjaxDataSource(data_url="http://127.0.0.1:8000/dates", polling_interval=200) ############# # Create data dict for the source, could be empty, filled with random data for testing ############# source.data=dict( dates=[date(2017, 2, i+1) for i in range(10)], downloads=[randint(0, 100) for i in range(10)]) columns = [ TableColumn(field="dates", title="Date", formatter=DateFormatter()), TableColumn(field="downloads", title="Downloads"), ] data_table = DataTable(source=source, columns=columns, width=400, height=280) show(WidgetBox(data_table)) 并想要A,B

    diagonal

    C,D

    获取M = (A+B)/2 v1 = B-M 我们可以利用 2D 向量v2(x,y)垂直且大小相同的事实:

    (y,-x)

    其余的很容易:

    v2 = (v1y,-v2x)
    
  2. 计算2个边缘基矢量

    basis vectors

    C = M - v2
    D = M + v2
    
  3. 使用点积检查内部范围

    dot

    U = C-A
    V = D-A
    

    给你dot(I,J) = (I.J) = (Ix*Jx) + (Iy*Jy) I的垂直投影(如果两个向量都是单位)或者相反,我们可以利用它来检测点J是否在正方形内:

    P
  4. 完成矢量的abs值就像这样计算:

    W = P-A
    tu = (U.W) / (|U|*|W|)
    tv = (V.W) / (|V|*|W|)
    if ((tu>=0.0)&&(tu<=1.0)&&(tv>=0.0)&&(tv<=1.0)) return inside;
     else return outside;