Linear regression using Least Squares

These are my programming notes. I doubt you’ll find anything useful.

Formula from: https://www.mathsisfun.com/data/least-squares-regression.html

/*
*Name: Least Squares Line (Finding gradient for a set of points) in Y = mX + c
*Role: Find line of best fit using Least Squares Method
*Input:
int xValues[] - Array containing all X coordinates
int yValues[] - Array containing all Y coordinates
numberOfElements - number of elements in the array
*Sample call:
int xCoordinates[10] = { 1,2,3,4,5,6,7,8,9,10};
int yCoordinates[10] = { 1,1,2,3,4,5,6,6,6,7};
LeastSquaresLine(xCoordinates, yCoordinates, 10);
*Sample output: Y = 0.721212 x + 0.393939
*/
void LeastSquaresLine(int xValues[], int yValues[], int numberOfElements)
{
//Initialize variables
int sumOfX = 0;
int sumOfY = 0;
int sumOfXYProducts = 0;
int sumOfSquareX = 0;

//Loop for summation
for(int i = 0; i < numberOfElements; i++)
{
sumOfX += xValues[i];
sumOfY += yValues[i];
sumOfXYProducts += xValues[i] * yValues[i];
sumOfSquareX += xValues[i] * xValues[i];
}

//Find the value for m, the gradient
double mCoefficient = (double) (numberOfElements * sumOfXYProducts - sumOfX * sumOfY) / (numberOfElements * sumOfSquareX - sumOfX * sumOfX);

//Finding value for c in Y = mX + c
int averageXValues = sumOfX / numberOfElements;
int averageYValues = sumOfY / numberOfElements;
double cCoefficient = averageYValues - mCoefficient * averageXValues;

//Print result
printf("Y = %f x + %f", mCoefficient, cCoefficient);
}