Skip to content

Instantly share code, notes, and snippets.

@mikbuch
Last active December 8, 2020 15:12
Show Gist options
  • Save mikbuch/d87c34489b20f170405827a5fccdcf06 to your computer and use it in GitHub Desktop.
Save mikbuch/d87c34489b20f170405827a5fccdcf06 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_multifit.h>
/* Interest rate */
double r[] = { 2.75, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.25,
2.25, 2.25, 2,2, 2, 1.75, 1.75, 1.75, 1.75,
1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75 };
/* Unemployment rate */
double u[] = { 5.3, 5.3, 5.3, 5.3, 5.4, 5.6, 5.5, 5.5,
5.5, 5.6, 5.7, 5.9, 6, 5.9, 5.8, 6.1,
6.2, 6.1, 6.1, 6.1, 5.9, 6.2, 6.2, 6.1 };
/* Stock index price */
double s[] = { 1464, 1394, 1357, 1293, 1256, 1254, 1234,
1195, 1159, 1167, 1130, 1075, 1047, 965, 943,
958, 971, 949, 884, 866, 876, 822, 704, 719 };
int main()
{
int n = sizeof(r)/sizeof(double);
gsl_matrix *X = gsl_matrix_calloc(n, 3);
gsl_vector *Y = gsl_vector_alloc(n);
gsl_vector *beta = gsl_vector_alloc(3);
for (int i = 0; i < n; i++) {
gsl_vector_set(Y, i, s[i]);
gsl_matrix_set(X, i, 0, 1);
gsl_matrix_set(X, i, 1, r[i]);
gsl_matrix_set(X, i, 2, u[i]);
}
double chisq;
gsl_matrix *cov = gsl_matrix_alloc(3, 3);
gsl_multifit_linear_workspace * wspc = gsl_multifit_linear_alloc(n, 3);
gsl_multifit_linear(X, Y, beta, cov, &chisq, wspc);
printf("Beta:");
for (int i = 0; i < 3; i++)
printf(" %g", gsl_vector_get(beta, i));
printf("\n");
gsl_matrix_free(X);
gsl_matrix_free(cov);
gsl_vector_free(Y);
gsl_vector_free(beta);
gsl_multifit_linear_free(wspc);
}
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment