Postgresql method for finding the slope of a line and forcing through origin

2k Views Asked by At

I have a temporary table with 2 numeric columns, Y and X.

CREATE TEMP TABLE findslope(y numeric,x numeric);

Which I then populate with the desired X and Y for the line I'm trying to fit a least squares best fit line which I am currently using the following:

SELECT REGR_SLOPE(y, x) slope FROM findslope into slope_variable;

This works well, but is it possible to force the line through a point or to set the intercept? Specifically I'd like the line to go through the origin: 0,0.

2

There are 2 best solutions below

0
On BEST ANSWER

Below is the working code:

SELECT 
  sum(y*x) / sum(x*x) as slope
FROM findslope INTO slope_variable
0
On

Its been a while since I had to get this sort of math right, so verify this on your own. I'd start with Simple linear regression on wiki.

I think will do it:

SELECT regr_sxy(y,x)/regr_sxy(x,x) AS slope FROM findslope INTO slope_variable;