Regression Equations in cpp

This code contains 2 functions related to the regression lines concept, the first function just takes the necessary arguments and uses them to make the regression equations, while the 2nd function takes the input from the user and uses the data of x and y to calculate the necessary things to get the equations, and makes use of the 1st function to print the equations by passing the values to it.

Below is the code :-

#include <iostream>
#include<vector>
// #include<bits/stdc++.h>
using namespace std;

void make_regression_eq(float x_mean,float y_mean,float b_yx,float b_xy){
    /* 
     * To get the regrssion lines by giving the data like
     * the value of x_mean,y_mean,b_yx,b_xy, etc.
     */
     cout<<"Regression Equation for Y onto X\n";
     cout<<"y-("<<y_mean<<") = "<<b_yx<<"(x-"<<x_mean<<")"<<endl;
     cout<<"Regression Equation for X onto Y\n";
     cout<<"x-("<<x_mean<<") = "<<b_xy<<"(y-"<<y_mean<<")"<<endl;
}
void get_regression_lines(){
    /* 
     * To get the regression lines by giving the values of
     * x and y
     */
     
    float sum_xsq=0,sum_ysq=0,xy_prod=0;
    float x_sum=0,y_sum=0,n,x_mean,y_mean,b_yx,b_xy;
    
    cout<<"Enter the number of values in the data: ";
    cin>>n;
    vector<int> x(n),y(n);
    cout<<"Enter the values in the pattern--> x y(x_value 'space' y_value): ";
    for(int i=0;i<n;i++){
        cin>>x[i];
        x_sum+=x[i];
        cin>>y[i];
        y_sum+=y[i];
        sum_xsq+=x[i]*x[i];
        sum_ysq+=y[i]*y[i];
        xy_prod+=x[i]*y[i];
    }
    
    //  So here we have the sums of the x and y values respectively 
// and thus we can calculate the valus of x_mean and y_mean 
// respectively, just a simple optimization technique
    cout<<endl;
    // Calculating b_yx 
    b_yx=((n*xy_prod)-(x_sum*y_sum))/((n*sum_xsq)-(x_sum*x_sum));
    // Calculating b_xy
    b_xy=((n*xy_prod)-(x_sum*y_sum))/((n*sum_ysq)-(y_sum*y_sum));
    
    // Sample Data from the question of 6th September 2022, Maths class
// 4 2
    // 2 3
    // 3 2
    // 4 4
    // 2 4
    // cout<<x_sum<<" "<<y_sum<<endl;
    // for(int i=0;i<n;i++){
    //     cout<<"x: "<<x[i]<<"\n";
    //     cout<<"y: "<<y[i]<<"\n";
    // }
    x_mean=x_sum/n;
    y_mean=y_sum/n;
    // sum_xsq=0,sum_ysq=0,xy_prod=0,x_sum=0,y_sum=0,n,x_mean,
// y_mean,b_yx,b_xy;
    cout<<"sum_xsq: "<<sum_xsq<<", sum_ysq: "<<sum_ysq<<", "
"xy_prod: "<<xy_prod<<", x_sum: "<<x_sum<<", y_sum: "<<y_sum<<","
" x_mean: "<<x_mean<<", y_mean"<<y_mean<<", b_yx: "<<b_yx<<","
" b_xy: "<<b_xy<<endl;
    make_regression_eq(x_mean,y_mean,b_yx,b_xy);
}
int main() {
    get_regression_lines();
    // make_regression_eq(6,4,0.2394,0.58);
    // cout<<"hola Todo El Mundo!\n"; 
    return 0;

} 

Comments

Popular Posts