C# slope function

Pretty simple stuff here. Replicating rise over run in C#. Then grab this result and plug in for ‘m’ in y=mx+b.

Start by creating a new class for this. lets call that Slope.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Automation
{
    public class Slope
    {

        public static double SlopeFunc(double[] x_arr, double[] y_arr)
        {
 

            double n = x_arr.Length;
            double sumxy = 0, sumx = 0, sumy = 0, sumx2 = 0;
            for (int i = 0; i < x_arr.Length; i++)
            {
                sumxy += x_arr[i] * y_arr[i];
                sumx += x_arr[i];
                sumy += y_arr[i];
                sumx2 += x_arr[i] * x_arr[i];
            }
            return ((sumxy - sumx * sumy / n) / (sumx2 - sumx * sumx / n));
        }
    }
}

From here, we can call our new function

double[] itemsx = { 5,3};
double[] itemsy = { 10, 6 };

var slope = Slope.SlopeFunc(itemsx, itemsy);
Console.WriteLine("-----calc slope-----");
Console.WriteLine(slope);

Leave a Reply

Your email address will not be published. Required fields are marked *