 # Sin & cos accuracy (calculating polygon angles)

I try improve the angle calculation accuracy by using both acos() and asin() in their best accuracy ranges:

``````# Change angles in the polygon
# Polygon with odd number of single-point self-intersections has sum of change angles equal to zero
# At the moment looks complicated, especially the ca~+/-180 cases... How to decide?
# The acos seem inaccurate at near 0 and near 180 degrees cases. Adding asin needed?
# Using asin() for -45...45 and -180...-135 and 135...180 ranges and acos() for -135...-45 and 45...135 ranges.
# The problem looks hard to be divided into a parallel vector if-then case
# Prerequisite is that same point does not occur consequently
function [ca]=chga(m)
v=m(1:end,:)-[m(end-1,:); m(1:end-1,:)];
dp=v(1:end-1,1).*v(2:end,1)+v(1:end-1,2).*v(2:end,2);
cp=v(1:end-1,1).*v(2:end,2)-v(1:end-1,2).*v(2:end,1);
l=hypot(v(1:end,1),v(1:end,2));
l2=l(1:end-1,1).*l(2:end,1);
cosa=dp./l2;
sina=cp./l2;
csgn(cp>=0,1)=1; csgn(cp<0,1)=-1;
ssgn(dp>=0,1)=0; ssgn(dp<0,1)=-1;
cc=find((abs(cosa)<=0.70711));
sc=find((abs(cosa)>0.70711));
ca(cc)=acos(cosa(cc)).*csgn(cc);
ca(sc)=asin(sina(sc))+ssgn(sc)*pi;
ca(abs(ca)<16*eps)=0;
cc=ca>pi;
ca(cc)=ca(cc)-2*pi;
ca(ca<=-pi|ca>pi)=pi;
``````octave:3> m0=[0 0; 0 3; 3 3; 3 4; 4 5; 3 4; 3 0; 0 0];