Represent a given set of points by the best possible straight line | function to calculate m and c that best fit points represented by x [ ] and y [ ] ; Driver code
function bestApproximate ( x , y , n ) { let m , c , sum_x = 0 , sum_y = 0 , sum_xy = 0 , sum_x2 = 0 ; for ( let i = 0 ; i < n ; i ++ ) { sum_x += x [ i ] ; sum_y += y [ i ] ; sum_xy += x [ i ] * y [ i ] ; sum_x2 += Math . pow ( x [ i ] , 2 ) ; } m = ( n * sum_xy - sum_x * sum_y ) / ( n * sum_x2 - Math . pow ( sum_x , 2 ) ) ; c = ( sum_y - m * sum_x ) / n ; document . write ( " " + m ) ; document . write ( " " + c ) ; } let x = [ 1 , 2 , 3 , 4 , 5 ] ; let y = [ 14 , 27 , 40 , 55 , 68 ] ; let n = x . length ; bestApproximate ( x , y , n ) ;