Search code examples
trigonometrypascallazarus

How to use arccos in Lazarus (pascal)


I have to write a program to find out the angles of a triangle. For some reason I always get the message 'INVALID OPERATION' which results in the program crashing. Can someone help me?

function Winkela(a,b,c:real):float;
var alpha:real;
begin
     alpha:= (b*b)+(c*c)-(a*a)/(2*b*c);
     radtodeg(arccos(alpha));
end;

function Winkelb(a,b,c:real):float;
var beta:real;
begin
     beta:= (c*c)+(a*a)-(b*b)/(2*c*a);
     radtodeg(arccos(beta));
end;

function Winkelc(a,b,c:real):float;
var gamma:real;
begin
     gamma:= (a*a)+(b*b)-(c*c)/(2*a*b);
     radtodeg(arccos(gamma));
end;

procedure TForm1.Button1Click(Sender: TObject);
var a,b,c:real;
begin
     a:=strtofloat(edit1.text);
     b:=strtofloat(edit2.text);
     c:=strtofloat(edit3.text);
     edit4.text:=floattostr(Winkela(a,b,c));
     edit5.text:=floattostr(Winkelb(a,b,c));
     edit6.text:=floattostr(Winkelc(a,b,c));
end;  

Solution

  • You compute

    alpha := (b*b)+(c*c)-(a*a)/(2*b*c)
    

    which, given the context ("the angles of a triangle"), I assume should be an application of the law of cosines. But then the mistake is obvious. You want

    alpha := ((b*b)+(c*c)-(a*a))/(2*b*c).
    

    For instance, if a = 3, b = 4, and c = 5, then

    (b*b)+(c*c)-(a*a)/(2*b*c) = 16 + 25 - 9/40 = 40.775
    

    whereas

    ((b*b)+(c*c)-(a*a))/(2*b*c) = (16 + 25 - 9)/40 = 32/40 = 0.8.
    

    In the first case, you get cos α = 40.775 which clearly has no real solution, since cos α belongs to [−1, 1] for all real angles α. Hence, your real ArcCos function will raise an exception.

    In the latter case, there is no problem: cos α = 0.8 implies that there is an integer n such that α = ±arccos(0.8) + 2nπ.