0

I'm currently trying to make a calculator that calculates Mean / Median / IQR / Standard Deviation / Variance of a set of data and a set of frequencies. To get the Mean of a set of data, i had intended to use the Sum() function and Lambda expressions, however i ran into a problem with this code below.

public double stat_getMeanGrouped(double[] dataset, double[] frequency)
{
    return dataset.Sum(x => x * frequency[int.Parse(x.toString)] / (double)frequency.Sum();
}

stat_getMeanGrouped(new double[] {1,2,3}, new double[] {1,1,1}); should return 2 however returns an index outside of range exception.

I understand why the error is happening, i just need help amending it.

4
  • 2
    int.Parse(x.toString)?! Eeeehm, what? Just cast to int: (int)x. Commented Feb 1, 2023 at 14:01
  • my brain is hardly functioning at the minute, just want to get this piece of coding done, but that does make me feel stupid Commented Feb 1, 2023 at 14:02
  • 1
    I have no clue what the purpose of dataset is. You're using it to access frequencies by index, however indeices start at zero instead of one. So the first element is frequencies[0]. Maybe you just need to substract one from x? Commented Feb 1, 2023 at 14:08
  • What i'm trying to do here is multiply dataset[i] by frequency[i] then divide by the sum of frequency to get the mean, then i can use that in the variance / standard deviation calculations. I think i'm just going to stick to a for loop though, makes it so much simpler. Commented Feb 1, 2023 at 14:12

1 Answer 1

2

You need to use the index, you can get it from the Select overload, if you want to use LINQ:

public static double stat_getMeanGrouped(double[] dataset, double[] frequency)
{
    return dataset
        .Select((value, index) => (Value: value, Index: index))
        .Where(x => x.Index < frequency.Length) // just to be sure
        .Sum(x => x.Value * frequency[x.Index]) / (double)frequency.Sum();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.