#include <iostream>
#include <vector>
using namespace std;
// Fungsi untuk menghitung rata-rata dari elemen-elemen dalam vector
double mean(const vector<double>& v) {
double sum = 0.0;
for (double num : v) {
sum += num;
}
return sum / v.size();
}
// Fungsi untuk menghitung regresi linier
void linearRegression(const vector<double>& x, const vector<double>& y, double& slope, double& intercept) {
if (x.size() != y.size() || x.size() == 0) {
cerr << "Error: Vectors must be of the same size and non-empty." << endl;
return;
}
double x_mean = mean(x);
double y_mean = mean(y);
double numerator = 0.0;
double denominator = 0.0;
for (size_t i = 0; i < x.size(); ++i) {
numerator += (x[i] - x_mean) * (y[i] - y_mean);
denominator += (x[i] - x_mean) * (x[i] - x_mean);
}
slope = numerator / denominator;
intercept = y_mean - slope * x_mean;
}
int main() {
// Data
vector<double> x = {1, 2, 3, 4, 5}; // variabel independen
vector<double> y = {2, 4, 5, 4, 5}; // variabel dependen
double slope, intercept;
// Menghitung regresi linier
linearRegression(x, y, slope, intercept);
// Menampilkan hasil
cout << "Regresi Linier: y = " << slope << " * x + " << intercept << endl;
return 0;
}