Wednesday, April 30, 2008

Linq Goodies 2 - Calculating Standard Deviation

Check out the following function, which calculates the Standard Deviation of a given list of values:

private static double calcStdev(IEnumerable<double> values)
double avg = values.Average();
return Math.Sqrt( (values.Sum(d => Math.Pow(d - avg, 2))) / (values.Count() - 1) );

Extra sweet...

Note that I could have replaced (d - avg) with (d - values.Average()) , hence resulting in a single line instead of 2, but the performance hit isn't worth it.

It may not look very readable looking at it as a programmer, but if you look at the mathematical formula of standard deviation, the above code is much closer to it than anything I've previously seen in C*.

Linq Goodies 1 - Extracting a range from an array

Slowly but surely I'm starting to get the huge benefits Linq is bringing into our lives. Take a look at the following code snippet, which retrieves values from an array in a specified range:

var range = cData.Where((d, index) => index >= (i - 40) && index < (i));

No support for static Extension Methods - bummer!

I wanted to add an extension method to Debug, which would automatically write a given set of parameters separated with commas (to generate CSV files). However, since extension methods are not supported for static methods, and the Debug.WriteXXX are static - it's not possible. Bummer!

Yet another missing feature in C#/CLR ...

Monday, April 21, 2008

Excel WTF

This is an old one, but I'm always stunned by the fact that a major application such as Excel still has issues like this. I'm trying to view two copies of the same file, located in different folder (I want to check a specific cell to see if it was changed). For some obscure reason, Excel can't handle two simultaneously opened files with the same name, even if they reside in different folder (not that there is any option for them to do reside in the same folder, but that's beside the point).

"A document with the name 'blablabla.xls' is already open. You cannot open two documents with the same name, even if the documents are in different folders. To open the second document, either close the document that's currently open, or rename one of the documents."