Quick actions

cmd+k|ctrl+k

Navigation

Languages

Regresi linear 

Snippet info

Language

Cpp

Visibility

public

Author

karelerlangga67

Created

2024-08-28T06:42:51.053318Z

Updated

2024-08-28T06:42:51.053318Z

# include <iostream>
#include <vector>

using namespace std;

// Fungsi untuk menghitung rata-rata dari sebuah vektor
double mean(const vector<double>& vec) {
    double sum = 0.0;
    for(double val : vec) {
        sum += val;
    }
    return sum / vec.size();
}

// Fungsi untuk menghitung kovarians antara dua vektor
double covariance(const vector<double>& x, const vector<double>& y) {
    double x_mean = mean(x);
    double y_mean = mean(y);
    double covar = 0.0;
    for(size_t i = 0; i < x.size(); ++i) {
        covar += (x[i] - x_mean) * (y[i] - y_mean);
    }
    return covar / x.size();
}

// Fungsi untuk menghitung variansi dari sebuah vektor
double variance(const vector<double>& vec) {
    double vec_mean = mean(vec);
    double var = 0.0;
    for(double val : vec) {
        var += (val - vec_mean) * (val - vec_mean);
    }
    return var / vec.size();
}

int main() {
    // Contoh data
    vector<double> X = {1, 2, 3, 4, 5};
    vector<double> y = {1.2, 2.3, 3.1, 4.5, 5.2};

    // Hitung koefisien regresi linear
    double b1 = covariance(X, y) / variance(X); // Koefisien slope
    double b0 = mean(y) - b1 * mean(X);         // Koefisien intercept

    // Tampilkan hasil
    cout << "Koefisien slope (b1): " << b1 << endl;
    cout << "Koefisien intercept (b0): " << b0 << endl;

    return 0;
}
INFO