Search code examples
c#calculatorvariance

Finding variance


I'm trying to Add a static method to calculate the average of a, array of integers, Overload the method in a. to also calculate an array of doubles. Add a method to calculate the sum of an array of integers or doubles Add a method to calculate the variance in an array of integers or doubles. Add a method to calculate the standard deviation of an array of integers or doubles.

I've finished most of the code but ran into a problem when I created the method to calculate the variance.

I've tried different things in here but it always gives me an error, I believe that the Math.Pow is what is messing this up. Is there another way and possibly simpler way to compute the variance with the rest of the code?

class States
{
    private static int Sum(int[] a)
    {
        int sum = 0;

        for (int i = 0; i < a.Length; i++)
        {
            sum += a[i];
        }
        return sum;
    }

    private static double Average(int[] a)
    {
        int sum = Sum(a);
        double Avg = (double)sum / a.Length;
        return Avg;
    }

//this is where i am having trouble

    private static double Var(int[] a)

    {

        if (a.Length > 1)

        {

            double Avg = Average(a);

            double var = 0.0;



            foreach (int A in Average)

            {

                // Math.Pow to calculate variance? 

                var += Math.Pow((A - Average)), 2.0) 

            }

            return var;

        }

        else

        {

            return 0.0;

        }
        private static double StdDev(double var)
        {
            return Math.Sqrt(var);
        }
    }
}

"Foreach cannot operate on a method group"


Solution

  • class States
    {
        private static int Sum(int[] values)
        {
            int sum = 0;
            for (int i = 0; i < values.Length; i++)
            {
                sum += values[i];
            }
            return sum;
        }
    
        private static double Average(int[] values)
        {
            int sum = Sum(values);
            double avg = (double)sum / values.Length;
            return avg;
        }
    
        //this is where i am having trouble
        public static double Variance(int[] values)
        {
            if (values.Length > 1)
            {
                double avg = Average(values);
                double variance = 0.0;
                foreach (int value in values)
                {
                    // Math.Pow to calculate variance? 
                    variance += Math.Pow(value - avg, 2.0);
                }
                return variance / values.Length; // For sample variance
            }
            else
            {
                return 0.0;
            }
        }
    
        private static double StdDev(double var)
        {
            return Math.Sqrt(var);
        }
    }