Least Square Regression Line | C ++ program to find the regression line ; Function to calculate b ; sum of array x ; sum of array y ; for sum of product of x and y ; sum of square of x ; Function to find the least regression line ; Finding b ; Calculating a ; Printing regression line ; Driver code ; Statistical data
#include <bits/stdc++.h> NEW_LINE using namespace std ; double calculateB ( int x [ ] , int y [ ] , int n ) { int sx = accumulate ( x , x + n , 0 ) ; int sy = accumulate ( y , y + n , 0 ) ; int sxsy = 0 ; int sx2 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sxsy += x [ i ] * y [ i ] ; sx2 += x [ i ] * x [ i ] ; } double b = ( double ) ( n * sxsy - sx * sy ) / ( n * sx2 - sx * sx ) ; return b ; } void leastRegLine ( int X [ ] , int Y [ ] , int n ) { double b = calculateB ( X , Y , n ) ; int meanX = accumulate ( X , X + n , 0 ) / n ; int meanY = accumulate ( Y , Y + n , 0 ) / n ; double a = meanY - b * meanX ; cout << ( " Regression ▁ line : " ) << endl ; cout << ( " Y ▁ = ▁ " ) ; printf ( " % .3f ▁ + ▁ " , a ) ; printf ( " % .3f ▁ * X " , b ) ; } int main ( ) { int X [ ] = { 95 , 85 , 80 , 70 , 60 } ; int Y [ ] = { 90 , 80 , 70 , 65 , 60 } ; int n = sizeof ( X ) / sizeof ( X [ 0 ] ) ; leastRegLine ( X , Y , n ) ; }