交点Point1.Y和Y应该相等但是Point1.Y和Y.为何有所不同?

问题描述

假设我们有两行。

L1:y1 = m1.x1 + c1
L2:y2 = m2.x2 + c2
这样m1!= m2

intersection_X =(c2-c1)/(m1-m2)
交集Y = m1 *相交X + c1

此外,如果我们计算交点Y ,而W L2 ,即交点Y = m2 *交点X + c2
intersection_Y 应该都相等。
如果运行下面的代码并检查 point1.Y Y ,您会发现两者均不相等
认为这里的精度处理有问题。
由于存在这种差异,因此发生崩溃。
可以请一个人照亮吗?


#include <iostream>
#include<cmath>
#include<limits>

using namespace std;

#define FUZZ_GEN (1e-9)       //tolerance for vertical check
#define FEQUAL(a,b,fuzz)  (fabs(a - b) <= (fuzz))

struct Point {
    double X,Y;
};

class LineSegment {            //Line class

public:
    LineSegment(double x1,double y1,double x2,double y2);

    void IntersectionPoints(LineSegment side);        

    double X1,Y1,X2,Y2,M,C;
};

LineSegment::LineSegment(double fX1,double fY1,double fX2,double fY2)   //Constructor for line
    : X1(fX1),Y1(fY1),X2(fX2),Y2(fY2)
{
    if (FEQUAL(X1,FUZZ_GEN))     // if vertical,slope is inf.
    {
        M = C = std::numeric_limits<double>::infinity();        // slope undefined
    }
    else
    {

        M = (Y2 - Y1) / (X2 - X1);
        C = Y1 - (M * X1);
    }
}
void LineSegment::IntersectionPoints (LineSegment side) {

    Point point1;
    point1.X = (C - side.C) / (side.M - M);     //intersection point 1
    point1.Y = M * point1.X + C;
    
    double Y = side.M * point1.X + side.C;       // ?? Y != point1.Y
}

int main()
{
// data coming from lower level APIs. Can't be changed
    LineSegment side = LineSegment(10.267716536547709,//create first line
            6.8779527559055005,10.031496064106765,6.8779527559055005);

    LineSegment line = LineSegment(10.149606299212586,// create second line
        9.1220472440944818,10.149606296983265,4.2665936725507594);

    line.IntersectionPoints(side);  //call to calc intersection point 
    return  0;
}

解决方法

有一个有限个双精度浮点数。

这意味着在两个浮点数之间 有无限多个实数。浮点数之间存在巨大的空白-用无法代表的数字填充!

当您定义两条线时,它们的交点非常不可能恰好位于双精度浮点数上。它将位于数字之间的巨大空白中。

想象一下,您放大得如此之深,可以清楚地看到浮动数字之间的间隔。您可以像下面的图像一样可视化交点,其中网格线是浮点数:

Image of two line segments intersecting on a grid

如果此处的下角坐标x = 0 y = 0,则最接近交点的x轴值为x = 2。但是,如果您在x = 2处评估两条线,则对于C-D行,您将获得y = 2,对于A-B行,您将获得y = 3。为什么?因为这些线在(2,2)或(2,3)处不相交,所以它们在相交的点处相交。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...