3 points are collinear in 2d

风流意气都作罢 提交于 2019-12-01 04:12:07

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.

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?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!