Below is a C# function that calculates the best fit line for a given set of points, represented as a list of Tuple<double, double> where each tuple is a point (x, y):
using System;
using System.Collections.Generic;
public class BestFitLineCalculator
{
public static (double slope, double intercept) CalculateBestFitLine(List<Tuple<double, double>> points)
{
double sumX = 0, sumY = 0, sumXY = 0, sumX2 = 0;
int N = points.Count;
foreach (var point in points)
{
double x = point.Item1;
double y = point.Item2;
sumX += x;
sumY += y;
sumXY += x * y;
sumX2 += x * x;
}
double slope = (N * sumXY - sumX * sumY) / (N * sumX2 - sumX * sumX);
double intercept = (sumY - slope * sumX) / N;
return (slope, intercept);
}
}
class Program
{
static void Main()
{
List<Tuple<double, double>> points = new List<Tuple<double, double>>
{
Tuple.Create(1.0, 1.0),
Tuple.Create(2.0, 2.0),
Tuple.Create(3.0, 1.5),
// Add more points as needed...
};
var bestFitLine = BestFitLineCalculator.CalculateBestFitLine(points);
Console.WriteLine($"The best fit line has slope: {bestFitLine.slope} and y-intercept: {bestFitLine.intercept}");
}
}
This function will produce a slope and intercept that describe the best fit line. You can then use these to draw the line or make predictions at certain x values. Note that this is a simple implementation and doesn't include any error handling (for example, it doesn't check for a sufficient number of points or for points with identical x values, which would result in a division by zero). Depending on your application, you might need to add such checks.