Least Square 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 ; statistical data
function calculateB ( x , y ) { let n = x . length ; let sx = x . reduce ( ( a , b ) => a + b , 0 ) ; let sy = y . reduce ( ( a , b ) => a + b , 0 ) let sxsy = 0 ; let sx2 = 0 ; for ( let i = 0 ; i < n ; i ++ ) { sxsy += x [ i ] * y [ i ] ; sx2 += x [ i ] * x [ i ] ; } let b = ( n * sxsy - sx * sy ) / ( n * sx2 - sx * sx ) ; return b ; } function leastRegLine ( X , Y ) { let b = calculateB ( X , Y ) ; let n = X . length ; let meanX = X . reduce ( ( a , b ) => a + b , 0 ) / n ; let meanY = Y . reduce ( ( a , b ) => a + b , 0 ) / n ; let a = meanY - b * meanX ; document . write ( " " ) ; document . write ( " " ) ; document . write ( a . toFixed ( 3 ) ) ; document . write ( " " ) ; document . write ( b . toFixed ( 3 ) ) ; document . write ( " " ) ; } let X = [ 95 , 85 , 80 , 70 , 60 ] ; let Y = [ 90 , 80 , 70 , 65 , 60 ] ; leastRegLine ( X , Y ) ;