EtcMath.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. * Copyright 2015 The Etc2Comp Authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "EtcConfig.h"
  17. #include "EtcMath.h"
  18. namespace Etc
  19. {
  20. // ----------------------------------------------------------------------------------------------------
  21. // calculate the line that best fits the set of XY points contained in a_afX[] and a_afY[]
  22. // use a_fSlope and a_fOffset to define that line
  23. //
  24. bool Regression(float a_afX[], float a_afY[], unsigned int a_Points,
  25. float *a_fSlope, float *a_fOffset)
  26. {
  27. float fPoints = (float)a_Points;
  28. float fSumX = 0.0f;
  29. float fSumY = 0.0f;
  30. float fSumXY = 0.0f;
  31. float fSumX2 = 0.0f;
  32. for (unsigned int uiPoint = 0; uiPoint < a_Points; uiPoint++)
  33. {
  34. fSumX += a_afX[uiPoint];
  35. fSumY += a_afY[uiPoint];
  36. fSumXY += a_afX[uiPoint] * a_afY[uiPoint];
  37. fSumX2 += a_afX[uiPoint] * a_afX[uiPoint];
  38. }
  39. float fDivisor = fPoints*fSumX2 - fSumX*fSumX;
  40. // if vertical line
  41. if (fDivisor == 0.0f)
  42. {
  43. *a_fSlope = 0.0f;
  44. *a_fOffset = 0.0f;
  45. return true;
  46. }
  47. *a_fSlope = (fPoints*fSumXY - fSumX*fSumY) / fDivisor;
  48. *a_fOffset = (fSumY - (*a_fSlope)*fSumX) / fPoints;
  49. return false;
  50. }
  51. // ----------------------------------------------------------------------------------------------------
  52. //
  53. } // namespace Etc