3 points are collinear in 2d

后端 未结 2 1046
余生分开走
余生分开走 2021-01-12 08:02

I am trying to verify when 3 points (double) are collinear in 2-D. I have found different Pascal functions that return true if this is verified; those functions use integer

相关标签:
2条回答
  • 2021-01-12 09:01

    The scalar product equation you calculate is zero if and only if the three points are co-linear. However, on a finite precision machine you don't want to test for equality to zero but instead you test for zero up to some small tolerance.

    Since the equation can be negative as well as positive your test isn't going to work. It will return false positives when the equation evaluates to a large negative value. Thus you need to test that the absolute value is small:

    function Collinear(const x1, y1, x2, y2, x3, y3: Double): Boolean;
    const
      tolerance = 0.01;//need a rationale for this magic number
    begin
      Result := abs((x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1)) < tolerance;
    end;
    

    Exactly how to choose tolerance depends on information you haven't provided. Where do the values come from? Are they dimensional?

    0 讨论(0)
  • 2021-01-12 09:06

    David's code will work, but you should get the tolerance as a function of the parameters, like so:

    function Collinear(const x1, y1, x2, y2, x3, y3: Double): Boolean; inline;   
    var  
      tolerance: double;  
    begin  
      tolerance := abs(max(x1,x2,x3,y1,y2,y3)) * 0.000001;  
      Result := abs((x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1)) < tolerance;  
    end;  
    

    If you don't do that and use a constant instead you can run into weird errors with large values for x1..y3.

    0 讨论(0)
提交回复
热议问题