WorksheetFunction.Quartile 在 C# 中等效

WorksheetFunction.Quartile equivalent in c#

我们目前正在做一个 MS-Access to .Net 网页项目。在 MS-Access VBA 代码中,他们使用了 "WorksheetFunction.Quartile" 函数。请让我知道 C# 中的等效函数。

VBA 中的示例用法:

Q1 = WorksheetFunction.Quartile(arrY, 1)

我不知道有任何包装好的小功能,但会很有帮助。我建议安装 math.NET http://www.mathdotnet.com/

此处显示了 SortedArrayStatistics 中包含的所有内容 http://numerics.mathdotnet.com/api/MathNet.Numerics.Statistics/SortedArrayStatistics.htm

以下是我认为符合您需求的四分位数示例

using System;
using MathNet.Numerics.Statistics;
class Test
{
    static void Main()
    {
        double[] numbers = new double[] { 1, 2, 3, 4, 5 };
        double a = SortedArrayStatistics.Minimum(numbers);
        double b = SortedArrayStatistics.LowerQuartile(numbers);
        double c = SortedArrayStatistics.Median(numbers);
        double d = SortedArrayStatistics.UpperQuartile(numbers);
        double e = SortedArrayStatistics.Maximum(numbers);

        Console.WriteLine("{0}\n{1}\n{2}\n{3}\n{4}\n", a,b,c,d,e);
    }
}

输出

1
1.66666666666667
3
4.33333333333333
5

请使用以下C#代码

方法代码

  internal static double QUARTILE(double[] array, int nth_quartile)
    {
        Array.Sort(array);
        double dblPercentage = 0;

        switch (nth_quartile)
        {
            case 0:
                dblPercentage = 0; //Smallest value in the data set
                break;
            case 1:
                dblPercentage = 25; //First quartile (25th percentile)
                break;
            case 2:
                dblPercentage = 50; //Second quartile (50th percentile)
                break;

            case 3:
                dblPercentage = 75; //Third quartile (75th percentile)
                break;

            case 4:
                dblPercentage = 100; //Largest value in the data set
                break;
            default:
                dblPercentage = 0;
                break;
        }


        if (dblPercentage >= 100.0d) return array[array.Length - 1];

        double position = (double)(array.Length + 1) * dblPercentage / 100.0;
        double leftNumber = 0.0d, rightNumber = 0.0d;

        double n = dblPercentage / 100.0d * (array.Length - 1) + 1.0d;

        if (position >= 1)
        {
            leftNumber = array[(int)System.Math.Floor(n) - 1];
            rightNumber = array[(int)System.Math.Floor(n)];
        }
        else
        {
            leftNumber = array[0]; // first data
            rightNumber = array[1]; // first data
        }

        if (leftNumber == rightNumber)
            return leftNumber;
        else
        {
            double part = n - System.Math.Floor(n);
            return leftNumber + part * (rightNumber - leftNumber);
        }
    } 

测试代码

double FirstQuartile = QUARTILE(numbers, 1);
double Median = QUARTILE(numbers, 2);
double ThirdQuartile = QUARTILE(numbers, 3);