.NET ez 2012-11-11
只需將數字存入 List 帶入 Function 即可計算出結果。
/// <summary>
/// 平均值
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
static double AVG(List<double> val)
{
try
{
double _sum = SUM(val);
if (_sum > 0 && val.Count > 0)
{
double _avg = _sum / (double)val.Count;
return _avg;
}
else
return 0;
}
catch
{
return 0;
}
}
/// <summary>
/// 加總
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
static double SUM(List<double> val)
{
try
{
if (val.Count > 0)
return (from g in val select g).Sum();
else
return 0;
}
catch
{
return 0;
}
}
/// <summary>
/// 眾數
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
static double Mode(List<double> val)
{
try
{
val.Sort();
double num = val.First();
int count = 0;
double max_num = num;
int max_count = 0;
foreach (double v in val)
{
if (v == num)
count++;
else
{
if (max_count < count)
{
max_num = num;
max_count = count;
}
num = v;
count = 1;
}
}
return max_num;
}
catch
{
return 0;
}
}
/// <summary>
/// 調和平均數
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
static double HarmonicAverage(List<double> val)
{
try
{
int i = 0;
double num = 0;
foreach (double v in val)
{
if (v > 0)
{
i++;
num += 1 / v;
}
}
if (i > 0 && num > 0)
return i / num;
else
return 0;
}
catch
{
return 0;
}
}
/// <summary>
/// 幾何平均數
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
static double GeometricMean(List<double> val)
{
try
{
int r = 0;
double prod = 1;
foreach (double v in val)
{
if (prod * v > double.MaxValue)
{
prod = Math.Pow(prod, 1.0 / r);
r = 0;
}
r++;
prod *= v;
}
return Math.Pow(prod, 1.0 / r);
}
catch
{
return 0;
}
}標籤: .NET
本文章網址:
https://www.ez2o.com/Blog/Post/csharp-Average-Mode-Harmonic-Mean-Mathematics
https://www.ez2o.com/Blog/Post/301
https://www.ez2o.com/Blog/Post/csharp-Average-Mode-Harmonic-Mean-Mathematics
https://www.ez2o.com/Blog/Post/301
