0% found this document useful (0 votes)
39 views2 pages

Least Square Method

This document provides a C++ code implementation of the Least Squares Method for linear regression. It includes a function to calculate the slope and intercept of the best fit line based on user-provided data points. The main function prompts the user for input and displays the resulting linear equation.

Uploaded by

shubhyadav.ngp
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views2 pages

Least Square Method

This document provides a C++ code implementation of the Least Squares Method for linear regression. It includes a function to calculate the slope and intercept of the best fit line based on user-provided data points. The main function prompts the user for input and displays the resulting linear equation.

Uploaded by

shubhyadav.ngp
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

C++ Code for Least Squares Method (Linear Regression)

#include <iostream>
#include <vector>
using namespace std;
// Function to calculate Least Squares Method for a straight line y = ax + b
void leastSquares(const vector<double>& x, const vector<double>& y, int n, double& a,
double& b) {
double sumX = 0, sumY = 0, sumXY = 0, sumX2 = 0;
for (int i = 0; i < n; i++) {
sumX += x[i];
sumY += y[i];
sumXY += x[i] * y[i];
sumX2 += x[i] * x[i];
}
// Calculating slope (a) and intercept (b)
a = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX);
b = (sumY - a * sumX) / n;
}
int main() {
int n;
cout << "Enter number of data points: ";
cin >> n;
vector<double> x(n), y(n);
cout << "Enter x and y values:\n";
for (int i = 0; i < n; i++) {
cout << "x[" << i + 1 << "]: ";
cin >> x[i];
cout << "y[" << i + 1 << "]: ";
cin >> y[i];
}
double a, b;
leastSquares(x, y, n, a, b);
cout << "\nThe best fit line equation is: y = " << a << "x + " << b << endl;
return 0;
}

You might also like