Rick T
Rick T

Reputation: 3389

Why is Calculating with the Cosine function so much faster than with the Secant Trig function?

Why is Calculating with the Cosine function so much more faster than with the Secant Trig function? Is There a way to speed up the secant function?

When calculating using the cosine and secant trig functions the time it takes vary a lot.

Cosine = finally Done-elapsed time -36.7544sec- or -0.6126mins- or -0.0102hours- 
Secant = finally Done-elapsed time -43.2231sec- or -0.7204mins- or -0.0120hours-

The code I use to test this is below. I just rem'd out the secant or cosine line to test the speed of each one I wanted.

clear all, clc,tic

num_of_values=60000; %number of values to use
a1_dataset =linspace(0,10000,num_of_values)';% 
a1_idx = randi (numel (a1_dataset), num_of_values, 1);
a1=a1_dataset (a1_idx);

a2_dataset =linspace(0,.8,num_of_values)';% 
a2_idx = randi (numel (a2_dataset), num_of_values, 1);
a2=a2_dataset (a2_idx);

a3_dataset =linspace(-360,360,num_of_values)';% 
a3_idx = randi (numel (a3_dataset), num_of_values, 1);
a3=a3_dataset (a3_idx);

array1=[a1,a2,a3];
t_rebuilt=linspace(0,16000,16000);
sig_comb=zeros(1,length(t_rebuilt));
for rr=1:1:length(array1) 

    sig_comb=sig_comb+array1(rr,2)*cos (((array1(rr,1))*t_rebuilt)+array1(rr, 3));  %test using cosine
    %sig_comb=sig_comb+array1(rr,2)*sec (((array1(rr,1))*t_rebuilt)+array1(rr, 3)); %test using secant

end

fprintf('\nfinally Done-elapsed time -%4.4fsec- or -%4.4fmins- or -%4.4fhours-\n',toc,toc/60,toc/3600);

PS: I'm using Octave 3.8.1 Linux

Upvotes: 1

Views: 336

Answers (1)

Daniel
Daniel

Reputation: 36710

Octave does not have a native implementation of sec, it uses cos to do so. Check edit sec.m for details.

The difference is caused by

  • function calls of nargin in sec
  • function call overhead for sec
  • dividing the values

To get rid of the first two factors, use 1./cos(x) instead of sec(x). To get exactly the same speed, a native implementation of sec would be required.

Upvotes: 3

Related Questions