Mirror

How to measure the distance between two points (Views: 101)


Problem/Question/Abstract:

I need to measure a distance between two points to compute an intensity value. Currently I use

Dx := i - Cur.X;
Dy := j - Cur.Y;
Distance := Round(Sqrt(Dx * Dx + Dy * Dy));

Is there a faster way to compute this? Distance is an integer type so I was hoping to get a reasonably accurate solution as this method seems to produce. Problem is that it slows things down a bit.

Answer:

You can calculate the angle and then make a lookup table for the value to be used to multiply the Y-axis. Try this:


program DCDemo;

{$APPTYPE CONSOLE}

uses
  SysUtils, Math, My_Crt32;

const
  DegToRadFact = Pi / 180;
  RadToDegFact = 180 / Pi;

var
  DistSinArray: array[1..359] of Extended;

function Calcdist(const dX, dY: LongInt): LongInt;
var
  Angle, n: word;
begin
  if (dX <> 0) then
  begin
    if (dY <> 0) then
    begin
      Angle := Round(ArcTan(dY / dX) * RadToDegFact);
      Result := Round(dY / DistSinArray[Angle]);
    end
    else
      Result := dX;
  end
  else
    Result := dY;
end;

var
  dX, dY: LongInt;
begin
  {First time operation}
  for dX := 1 to 359 do
    DistSinArray[dX] := Sin(dX * DegToRadFact);
  Writeln('Geef dX: ');
  readln(dX);
  Writeln('Geef dY: ');
  readln(dY);
  Writeln(FloatToStr(Calcdist(dX, dY)));
  Readln;
end.

<< Back to main page