Reputation: 1699
I have an array of numbers which are prices of a stock as given below:
double[] xyz=new double{ 10.1, 20.34, 35.46, 78.34, 98.67, 43.73 ........}
Now, I want to find the average of stock based on time:
1st min = Average(10.1) = 10.1
2nd min = Average(10.1 + 20.34) = 15.22
3rd min = Average(10.1 + 20.34 + 35.46) = 21.96
One way of doing this is to loop minutes times(1,2,3,4...) and find the average. But, as my list is very huge, this can become a performance issue.
Is there any other way of finding average each time?
Thanks a lot.
Mahesh
Upvotes: 0
Views: 2114
Reputation: 18306
double[] xyz=new double{ 10.1, 20.34, 35.46, 78.34, 98.67, 43.73 ........ }
double[] averages = new double[xyz.Length];
averages[0] = xyz[0];
for(int i = 1; i < xyz.Length; i++)
{
averages[i] = (((averages[i-1] * i) + xyz[i])/i+1);
}
Upvotes: 0
Reputation: 156
You need some form of persistence.
Perhaps an object ? AverageObj that contains a counter and a sum field.
Upvotes: 0
Reputation: 60105
You can calculate them in O(n)
(in single pass) by using following recursive formula:
An
means n-th minute average, Vn
- n-th minute price.
An = (An-1 * (n - 1) + Vn) / n
So you loop and keep previous An
.
PS: If i understood you correctly you want to find average of prices for every minute, not single average.
Upvotes: 2
Reputation: 272762
Yes, maintain a running sum:
sum = 0;
num = 0;
foreach (element i)
{
sum += i;
num ++;
average = sum / num;
}
Choose a big enough type for sum
such that it won't ever overflow.
Upvotes: 6