Mathematics

Round float number with limit

Posted in Mathematics

This example shows, how to round float number, if you want to get result with specified number of numerals after delimiter.

procedure TForm1.Button1Click(Sender: TObject);
var
  Num, Pow: Real;
  Count: Integer;
begin
  Num:=StrToFloat(Edit1.Text);
  Count:=StrToInt(Edit2.Text);
  Pow:=Power(10,Count);
  Num:=Num*Pow;
  Label3.Caption:=FloatToStr(Round(Num)/Pow);
end;

Integer/fractional part of number

Posted in Mathematics

Use Int function, if you want to get integer part of real number and Fruc function for getting fractional part of it.

procedure TForm1.Button1Click(Sender: TObject);
var
  Number: Real;
begin
  Number:=StrToFloat(Edit1.Text);
  Label2.Caption:=
    'Integer part is '+
    FloatToStr(Int(Number));
  Label3.Caption:=
    'Fractional part is '+
    FloatToStr(Frac(Number));
end;

Get vulgar fraction from decimal

Posted in Mathematics

This is a algorithm for getting vulgar fraction from decimal fraction.

function HOD(x, y: Integer): Integer;
begin
  if (x mod y)<>0 then
    Result:=HOD(y, x mod y)
  else Result:=y;
end;

procedure Elements(St: string; var x,y: Real);
var
  Denom, i, L, Max: Integer;
begin
  Denom:=1;
  L:=Length(St);
  for i:=1 to L do
    Denom:=Denom*10;
  Max:=HOD(Denom, StrToInt(St));
  y:=Denom/Max;
  x:=StrToInt(St)/Max;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  P, Max: Integer;
  St: string;
  x, y: Real;
begin
  P:=Pos('.', Edit1.Text);
  if P<>0 then
  begin
    Label6.Caption:=Copy(Edit1.Text, 1, P-1);
    St:=Copy(Edit1.Text, P+1, Length(Edit1.Text)-P);
    Elements(St, x, y);
    Label2.Caption:=FloatToStr(x);
    Label4.Caption:=FloatToStr(y);
  end
  else
  begin
    Label6.Caption:=Edit1.Text;
    Label2.Caption:='1';
    Label4.Caption:='1';
  end;
end;
 

Get distance between 2 points

Posted in Mathematics

Use Distance function for detecting distance between 2 points. XPos and YPos are coordinates of the first point and X and Y are coordinates of the second point.

uses Math;
...
function Distance(XPos, YPos, X, Y: Real): Real;
begin
  Result:=sqrt(
    Power(XPos-X,2)+Power(YPos-Y,2));
end;