Through-Origin Linear Regression
Problem statement
You are given a nonempty list of observed points points[i] = [x_i, y_i]. Fit the no-intercept model predicted_y = w * x by choosing one real-valued weight w that minimizes the mean squared error.
MSE(w) = sum((y_i - w * x_i)^2) / points.length
For this exercise, each feature and label is an integer. Repeated observations remain separate samples. Return the minimizing weight as a floating-point number. Do not fit a bias or intercept.
If every feature is zero, every weight gives the same error; return 0.0. Otherwise the minimizing weight is unique. Answers are accepted with relative-or-absolute tolerance 10^-9.
Function
fitThroughOrigin(points: int[][]) → doubleExamples
Example 1
points = [[1,2],[2,4],[3,6]]return = 2.0All observations lie on y = 2x, so the zero-loss weight is 2.
Example 2
points = [[1,3],[2,5],[3,7]]return = 2.4285714285714284The numerator is 34 and the denominator is 14. The weight is 17/7; fitting an intercept would solve a different problem.
Example 3
points = [[0,4],[0,-3]]return = 0.0All x values are zero, so changing the weight changes no prediction. The stated convention returns 0.
Constraints
1 <= points.length <= 10000.- Each point contains exactly two integers
[x_i, y_i]. -10000 <= x_i, y_i <= 10000.- Use sufficiently wide arithmetic for products and sums; each accumulator has magnitude at most
10^12.