Least Square Regression Line | Java 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
import java . util . Arrays ; public class GFG { private static double calculateB ( int [ ] x , int [ ] y ) { int n = x . length ; int sx = Arrays . stream ( x ) . sum ( ) ; int sy = Arrays . stream ( y ) . sum ( ) ; 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 ; } public static void leastRegLine ( int X [ ] , int Y [ ] ) { double b = calculateB ( X , Y ) ; int n = X . length ; int meanX = Arrays . stream ( X ) . sum ( ) / n ; int meanY = Arrays . stream ( Y ) . sum ( ) / n ; double a = meanY - b * meanX ; System . out . println ( " Regression ▁ line : " ) ; System . out . print ( " Y ▁ = ▁ " ) ; System . out . printf ( " % .3f " , a ) ; System . out . print ( " ▁ + ▁ " ) ; System . out . printf ( " % .3f " , b ) ; System . out . print ( " * X " ) ; } public static void main ( String [ ] args ) { int X [ ] = { 95 , 85 , 80 , 70 , 60 } ; int Y [ ] = { 90 , 80 , 70 , 65 , 60 } ; leastRegLine ( X , Y ) ; } }