Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package regression;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Scanner;
- public class Functions
- {
- public void printList(List<Double> list)
- {
- int listSize = list.size();
- for(int i=0;i<listSize;i++)
- {
- System.out.println("Item "+(i+1)+" : "+list.get(i));
- }
- }
- public void printList(String listName,List<Double> list)
- {
- int listSize = list.size();
- System.out.println("In "+listName+" : ");
- for(int i=0;i<listSize;i++)
- {
- System.out.println("Item "+(i+1)+" : "+list.get(i));
- }
- }
- public double sumOfList(List<Double> list)
- {
- int listSize = list.size();
- double sum = 0;
- for(int i=0;i<listSize;i++)
- {
- sum=sum+list.get(i);
- }
- return sum;
- }
- public List<Double> makeSumOfSquareList(List<Double> list)
- {
- List<Double> newList = new ArrayList();
- int listSize = list.size();
- for(int i=0;i<listSize;i++)
- {
- double x = list.get(i);
- double newX = Math.pow(x,2);
- newList.add(newX);
- }
- return newList;
- }
- public double calculateB(List<Double> xList,List<Double> yList,int n)
- {
- double b = 0;
- double sumXY=0,sumXsumY=0,sumXsquare=0,squareOfsumX=0;
- List<Double> customList = new ArrayList();
- for(int i=0;i<n;i++)
- {
- double u = xList.get(i);
- double v = yList.get(i);
- double w = u*v;
- customList.add(w);
- }
- sumXY= sumOfList(customList);
- double x1 = sumOfList(xList);
- double x2 = sumOfList(yList);
- sumXsumY=x1*x2;
- sumXsquare=sumOfList(makeSumOfSquareList(xList));
- squareOfsumX=Math.pow(sumOfList(xList),2);
- b = ( (n*sumXY) - sumXsumY ) / ( (n*sumXsquare ) - (squareOfsumX) ) ;
- return b;
- }
- public double calculateA(List<Double> xList,List<Double> yList,int n)
- {
- double A = 0;
- double sumY = sumOfList(yList);
- double sumX = sumOfList(xList);
- double B = calculateB(xList,yList,n);
- A= ( sumY/n ) - ( ( B*sumX ) / n );
- return A;
- }
- }
- public class Main
- {
- public static List<Double> listX = new ArrayList();
- public static List<Double> listY = new ArrayList();
- public static void inputData2D(int totalDataSize)
- {
- Scanner scanner = new Scanner(System.in);
- for(int i=0;i<totalDataSize;i++)
- {
- System.out.print("Enter x"+(i+1)+" : ");
- double x = scanner.nextDouble();
- listX.add(x);
- System.out.print("Enter y"+(i+1)+" : ");
- double y = scanner.nextDouble();
- listY.add(y);
- }
- }
- public static void main(String[] args)
- {
- Functions functions = new Functions();
- Scanner scanner = new Scanner(System.in);
- System.out.print("How many (x,y) inputs : ");
- int totalData = scanner.nextInt();
- inputData2D(totalData);
- double b = functions.calculateB(listX, listY, totalData);
- double a = functions.calculateA(listX, listY, totalData);
- System.out.println("The straight line is : y="+a+"+"+b+"x");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement