function z=mycos(x);
% function MYCOS
%   Computes cos(x) quite accurately (maximum relative error 
%   less than 3e-12) by reduction to the interval [0,pi/2) and
%   N=10 degree Chebyshev polynomial approximation.
%   *Not vectorized.*

piovertwo=1.5707963267949;
pi=3.14159265358979;
twopi=6.28318530717959;

x=abs(x);
n=floor(x/twopi);
x=x-n*twopi; % now x in interval [0,2 pi)
if x>=pi, negflag=1; x=x-pi; else negflag=0; end % now in [0,pi)
if x>=piovertwo, negflag=1-negflag; x=pi-x; end
% x is now in [0,pi/2) so use polynomial approximation
   
% use Chebyshev 6th degree poly, coeffs generated by:
%   N=10; xx=(pi/4)*(cos((0:N)*pi/N)+1);
%   p=polyfit(cos(xx),N);
p=[-1.92144783152994e-7 -4.06957930123976e-7 2.57457462171312e-5 ...
   -1.2806045985044e-6  -0.00138781232554854 -5.6297851335203e-7 ...
    0.0416668432430937  -3.04708950507068e-8 -0.499999997581208 ...
   -5.68365305651918e-11 1];

z=polyval(p,x);  % uses Horner's evaluation of polynomial
if negflag, z=-z; end