Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do this simple weighted average in LINQ?

Tags:

linq

I'm just curious if this could be done in a single LINQ statement. I need to do a simple weighted average like this:

IEnumerable<double> values = { v0, v1, v2, v3, ...}
WeightedAverage = (((v0 + v1) / 2 + v2) / 2 + v3) / 2 ...
like image 720
newman Avatar asked May 19 '11 13:05

newman


People also ask

How do you find the average in Linq?

In LINQ, you can find the average of the given sequence by using the Average method. This method returns the average of the elements present in the given sequence or collection. It returns nullable, non-nullable decimal, double, floats, int, etc. values.

How is simple average calculated?

The simple average of a set of observations is computed as the sum of the individual observations divided by the number of observations in the set.

How is weighted ASP calculated?

In order to calculate your weighted average price per share, simply multiply each purchase price by the amount of shares purchased at that price, add them together, and then divide by the total number of shares.

How do you create a weighted average in python?

Calculate a Weighted Average in Pandas Using NumpyThe numpy library has a function, average() , which allows us to pass in an optional argument to specify weights of values. The function will take an array into the argument a= , and another array for weights under the argument weights= .


1 Answers

double average = values.Aggregate((x, y) => (x + y) / 2.0);
like image 114
dlev Avatar answered Jan 03 '23 11:01

dlev