You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

lin_reg.cc 1.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /**********************************************************
  2. This software is part of J.-S. Caux's ABACUS library.
  3. Copyright (c) J.-S. Caux.
  4. -----------------------------------------------------------
  5. File: lin_reg.cc
  6. Purpose: Linear regression
  7. ***********************************************************/
  8. #include "ABACUS.h"
  9. using namespace std;
  10. namespace ABACUS {
  11. void lin_reg (Vect_DP x, Vect_DP y, Vect_DP sigma, DP& a, DP& b, DP& chisq)
  12. {
  13. // Performs simple linear regression on data
  14. int Npts = x.size();
  15. DP S = 0.0;
  16. DP Sx = 0.0;
  17. DP Sy = 0.0;
  18. DP Stt = 0.0;
  19. Vect_DP t(0.0, Npts);
  20. for (int i = 0; i < Npts; ++i) {
  21. S += 1.0/(sigma[i] * sigma[i]);
  22. Sx += x[i]/(sigma[i] * sigma[i]);
  23. Sy += y[i]/(sigma[i] * sigma[i]);
  24. }
  25. for (int i = 0; i < Npts; ++i) {
  26. t[i] = (x[i] - Sx/S)/sigma[i];
  27. Stt += t[i] * t[i];
  28. }
  29. a = 0.0;
  30. b = 0.0;
  31. for (int i = 0; i < Npts; ++i) {
  32. b += t[i] * y[i]/sigma[i];
  33. }
  34. b /= Stt;
  35. a = (Sy - Sx * b)/S;
  36. chisq = 0.0;
  37. for (int i = 0; i < Npts; ++i) {
  38. chisq += (y[i] - a - b * x[i]) * (y[i] - a - b * x[i]) / (sigma[i] * sigma[i]);
  39. }
  40. return;
  41. }
  42. void lin_reg (Vect_DP x, Vect_DP y, DP& a, DP& b, DP& chisq)
  43. {
  44. // Assumes all sigma == 1
  45. Vect_DP sigma(1.0, x.size());
  46. lin_reg (x, y, sigma, a, b, chisq);
  47. return;
  48. }
  49. }