C++ Code for Least Squares Method

            
#include <iostream>
#include <vector>
#include <cmath>

using namespace std;

// Function to perform least squares fitting
// Fits a line of the form y = a*x + b to given data points
void leastSquaresFit(const vector<double>& x, const vector<double>& y, double& a, double& b) {
    int n = x.size();
    double sum_x = 0.0, sum_y = 0.0, sum_xy = 0.0, sum_x2 = 0.0;

    for (int i = 0; i < n; ++i) {
        sum_x += x[i];
        sum_y += y[i];
        sum_xy += x[i] * y[i];
        sum_x2 += x[i] * x[i];
    }

    double denom = n * sum_x2 - sum_x * sum_x;
    if (denom == 0) {
        // Handle division by zero
        cerr << "Error: Division by zero!" << endl;
        return;
    }

    a = (n * sum_xy - sum_x * sum_y) / denom;
    b = (sum_x2 * sum_y - sum_x * sum_xy) / denom;
}

int main() {
    // Sample data
    vector<double> x = {1, 2, 3, 4, 5}; // Sample x values
    vector<double> y = {2.3, 3.6, 4.8, 6.1, 7.4}; // Sample y values

    double a, b;
    leastSquaresFit(x, y, a, b);

    // Output the results
    cout << "Least Squares Fit: y = " << a << " * x + " << b << endl;

    return 0;
}