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.
 
 
 
 
 

57 lines
2.1 KiB

  1. /*
  2. * aptdec - A lightweight FOSS (NOAA) APT decoder
  3. * Copyright (C) 2019-2022 Xerbo (xerbo@protonmail.com)
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. #include "algebra.h"
  19. #include <math.h>
  20. // Find the best linear equation to estimate the value of the
  21. // dependent variable from the independent variable
  22. linear_t linear_regression(const float *independent, const float *dependent, size_t len) {
  23. // Calculate mean of the dependent and independent variables (this is the centoid)
  24. float dependent_mean = 0.0f;
  25. float independent_mean = 0.0f;
  26. for (size_t i = 0; i < len; i++) {
  27. dependent_mean += dependent[i] / (float)len;
  28. independent_mean += independent[i] / (float)len;
  29. }
  30. // Calculate slope
  31. float a = 0.0f;
  32. {
  33. float a_numerator = 0.0f;
  34. float a_denominator = 0.0f;
  35. for (size_t i = 0; i < len; i++) {
  36. a_numerator += (independent[i] - independent_mean) * (dependent[i] - dependent_mean);
  37. a_denominator += powf(independent[i] - independent_mean, 2.0f);
  38. }
  39. a = a_numerator / a_denominator;
  40. }
  41. // We can now solve for the y-intercept since we know the slope
  42. // and the centoid, which the line must pass through
  43. float b = dependent_mean - a * independent_mean;
  44. // printf("y(x) = %fx + %f\n", a, b);
  45. return (linear_t){a, b};
  46. }
  47. float linear_calc(float x, linear_t line) { return x * line.a + line.b; }
  48. float quadratic_calc(float x, quadratic_t quadratic) { return x * x * quadratic.a + x * quadratic.b + quadratic.c; }