Array and Strings – Algebra – Problem #7
IIT Kharagpur CS10001 / CS11001 Programming and Data Structures Lab Question Archive
Problem Statement
In this question, we will find the straight line equation that best fits a given set of points. Consider a given set of ordered pairs of points (x1, y1),(x2, y2), · · · ,(xn, yn). Our goal is to approximate the parameters m and b in the straight line equation y = mx + b. This can be achieved by the following steps: Step-1 : Calculate the mean of the x -values and the mean of the y-values as follows: x¯ = Pn i=1 xi n , y¯ = Pn i=1 yi n Step-2 : The slope is computed as, m = Pn i=1(xi − x¯)(yi − y¯) Pn i=1(xi − x¯) 2 Step-3 : Compute the y-intercept of the line as, b = ¯y − mx¯ Step-4 : Use the slope m and the y-intercept b to form the equation of the line. Your task is to take the x and y coordinates of the points as input from the user, store them in two different arrays (you may assume that the number of data points are fixed, so you can declare the array sizes accordingly), and compute the straight line equation based on the above formulas. Example: Input: x -coordinates: 8, 2, 11, 6, 5, 4, 12, 9, 6, 1 y-coordinates: 3, 10, 3, 6, 8, 12, 1, 4, 9, 14 Output: m = −1.1, b = 14.0, line equation y = −1.1x + 14.0