C# 3.0 一行求方差

某python程序员说用C#求方差需要五十行。于是我试了试

python
def variance (*l):
      return sum([(i – sum(l) * 1.0 / len(l)) ** 2 for i in l]) / len(l)

C#

Func<List<double>, double> variance = numbers => 
                (from n in numbers select Math.Pow((n - numbers.Sum() / numbers.Count), 2)).Sum() / numbers.Count;

Console.Write(variance(new List<double> { 1, 2, 5, 6 }));
我很久没干过这么无聊的事情了……

Advertisements
This entry was posted in .NET. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s