Software Archive
Read-only legacy content
17060 Discussions

Calling Dr Stack!

rahzan
New Contributor I
1,473 Views
let's say we want to calculate the std.dev of an array of #'s in a function. Traditionally one sets up loops to get the sum and the variance etc.
Consider the following alternative:

pure real(4) function getSdev(X,first,last)
integer,intent(in):: first,last
real(4),intent(in),volatile:: X(first:last)
ave=SUM(X(last:first))/(last-first+1)
std=sqrt(SUM(X**2)-ave**2)/(last-first)

1. Can the SUM function improve the speed over a looped sum?

2. Since we do not know the size of the array AND that X**2 is stored on the STACK, for a large array, can this cause problems in either in lack of stack size, or speed?

Thanks,
Tim
0 Kudos
1 Reply
grtoro
Beginner
1,473 Views
As an aside, some authors recommend using two loops (or, I suppose, two SUM's). The first one calculates the mean, the second one sums (X-mean)**2. This way, you avoid roundoff errors (and the negative variances they produce sometimes).

Gabriel
0 Kudos
Reply