Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

3 points are collinear in 2d

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 to specify X and Y coordinates. I need a more precise calculation at least to the first 3 digits of the decimal part of X and Y expressed as double type. Who can help me with this?

I found this function:

function Collinear(x1, y1, x2, y2, x3, y3: Double): Boolean;
begin
  Result := (((x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1)) = 0);
end;

But I guess the calculation would never be 0. Should I use something like that?

function Collinear(x1, y1, x2, y2, x3, y3: Double): Boolean;
begin
  Result := (((x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1)) < 0.01);
end;
like image 529
marcostT Avatar asked Feb 15 '11 21:02

marcostT


1 Answers

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?

like image 85
David Heffernan Avatar answered Sep 23 '22 16:09

David Heffernan