Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.

Statistics

Part of TutorialIntermediate

Description

Demonstrates calculating linear regression statistics.

Example

```import std.stdio;

double average(double[] r)
{
double t = 0;

for(int i=0; i < r.length; i++)
t += r[i];

return (t / (cast(double) r.length));
}

double beta1(double[] x, double[] y, double x_bar, double y_bar)
{
int l;

if (x.length != y.length)
{
writefln("x and y really should be the same length!");

// Set length as the shorter series and move on...

if(x.length < y.length) l = x.length;
else l = y.length;
}
else l = x.length;

double top_sum, btm_sum;

top_sum = 0;

for(int i = 0; i < l; i++)
top_sum += (x[i] - x_bar) * (y[i] - y_bar);

btm_sum = 0;

for(int i = 0; i < l; i++)
btm_sum += ((x[i] - x_bar) * (x[i] - x_bar));

}

double beta0(double x_bar, double y_bar, double b1)
{
return y_bar - (b1 * x_bar);
}

int main()
{
double[] x;

x.length = 10;

x[0] = 1;
x[1] = 2;
x[2] = 3;
x[3] = 4;
x[4] = 5;
x[5] = 6.5;
x[6] = 7;
x[7] = 7.5;
x[8] = 8;
x[9] = 8.5 ;

double[] y;

y.length = 10;

y[0] = 1;
y[1] = 2;
y[2] = 3;
y[3] = 3.2;
y[4] = 3.4;
y[5] = 4;
y[6] = 4.2;
y[7] = 4.3;
y[8] = 4.35;
y[9] = 4.37;

double x_bar, y_bar;

x_bar = average(x);
y_bar = average(y);

double b1, b0;
b1 = beta1(x, y, x_bar, y_bar);
b0 = beta0(x_bar, y_bar, b1);

writefln("b1: %f", b1);
writefln("b0: %f", b0);

return 0;
}
```

Source

Based on stat.html by jcc7.