Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Try this code. It fits <code>y = mx + b</code> to your (x,y) data.</p> <p>The arguments to <code>linreg</code> are</p> <pre><code>linreg(int n, REAL x[], REAL y[], REAL* b, REAL* m, REAL* r) n = number of data points x,y = arrays of data *b = output intercept *m = output slope *r = output correlation coefficient (can be NULL if you don't want it) </code></pre> <p>The return value is 0 on success, !=0 on failure.</p> <p>Here's the code</p> <pre><code>#include "linreg.h" #include &lt;stdlib.h&gt; #include &lt;math.h&gt; /* math functions */ //#define REAL float #define REAL double inline static REAL sqr(REAL x) { return x*x; } int linreg(int n, const REAL x[], const REAL y[], REAL* m, REAL* b, REAL* r){ REAL sumx = 0.0; /* sum of x */ REAL sumx2 = 0.0; /* sum of x**2 */ REAL sumxy = 0.0; /* sum of x * y */ REAL sumy = 0.0; /* sum of y */ REAL sumy2 = 0.0; /* sum of y**2 */ for (int i=0;i&lt;n;i++){ sumx += x[i]; sumx2 += sqr(x[i]); sumxy += x[i] * y[i]; sumy += y[i]; sumy2 += sqr(y[i]); } REAL denom = (n * sumx2 - sqr(sumx)); if (denom == 0) { // singular matrix. can't solve the problem. *m = 0; *b = 0; if (r) *r = 0; return 1; } *m = (n * sumxy - sumx * sumy) / denom; *b = (sumy * sumx2 - sumx * sumxy) / denom; if (r!=NULL) { *r = (sumxy - sumx * sumy / n) / /* compute correlation coeff */ sqrt((sumx2 - sqr(sumx)/n) * (sumy2 - sqr(sumy)/n)); } return 0; } </code></pre> <h1>Example</h1> <p>You can run <a href="http://www.tutorialspoint.com/compile_c_online.php?PID=0Bw_CjBb95KQMeXVFb1ZGRERGak0" rel="noreferrer">this example online</a>.</p> <pre><code>int main() { int n = 6; REAL x[6]= {1, 2, 4, 5, 10, 20}; REAL y[6]= {4, 6, 12, 15, 34, 68}; REAL m,b,r; linreg(n,x,y,&amp;m,&amp;b,&amp;r); printf("m=%g b=%g r=%g\n",m,b,r); return 0; } </code></pre> <h2>Here is the output</h2> <pre><code>m=3.43651 b=-0.888889 r=0.999192 </code></pre> <h2>Here is the Excel plot and linear fit (for verification).</h2> <p>All values agree exactly with the C code above (note C code returns <code>r</code> while Excel returns <code>R**2</code>).</p> <p><a href="https://i.stack.imgur.com/2xSvb.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/2xSvb.jpg" alt="Excel version of fit"></a></p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload