Skip to content

Instantly share code, notes, and snippets.

@Yegorsh
Last active January 5, 2022 21:07
Show Gist options
  • Select an option

  • Save Yegorsh/a51559986c0cad3a9c099486231fd9d9 to your computer and use it in GitHub Desktop.

Select an option

Save Yegorsh/a51559986c0cad3a9c099486231fd9d9 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main(){
int n;
cout << "Введите количество пар точек" << endl;
cin >> n;
double x[n], y[n], a, b;
cout << "Введите значения абсцисс точек\n";
for (int i=0; i<n; i++){
cin >> x[i];
}
cout << "Введите значения ординат точек\n";
for (int i=0; i<n; i++){
cin >> y[i];
}
double xsum=0, x2sum=0, ysum=0, xysum=0;
for (int i=0; i<n; i++){
xsum += x[i]; //calculating sigma(x_i)
ysum += y[i]; //calculating sigma(y_i)
x2sum += pow(x[i],2); //calculating sigma(x^2_i)
xysum += x[i]*y[i]; //calculating sigma(x_i * y_i)
}
a = (n*xysum - xsum*ysum)/(n*x2sum - xsum*xsum); //calculating the slope
b = (x2sum*ysum - xsum*xysum)/(x2sum*n - xsum*xsum);
double y_fit[n];
for (int i=0; i<n; i++){
y_fit[i] = a*x[i] + b;
}
cout << "S.no" << setw(5) << "x" << setw(19) << "y" << setw(19) << "y(fitted)" << endl;
for (int i=0; i<n; i++){
cout << i+1 << "." << setw(8) << x[i] << setw(15) << y[i] << setw(18) << y_fit[i] << endl;
}
cout << "\nУравнение найденной прямой\n" << a << "x + " << b << endl; //print the best fit line
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment