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 
17 #include "EtcConfig.h"
18 #include "EtcMath.h"
19 
20 namespace Etc
21 {
22 
23 	// ----------------------------------------------------------------------------------------------------
24 	// calculate the line that best fits the set of XY points contained in a_afX[] and a_afY[]
25 	// use a_fSlope and a_fOffset to define that line
26 	//
Regression(float a_afX[],float a_afY[],unsigned int a_Points,float * a_fSlope,float * a_fOffset)27 	bool Regression(float a_afX[], float a_afY[], unsigned int a_Points,
28 					float *a_fSlope, float *a_fOffset)
29 	{
30 		float fPoints = (float)a_Points;
31 
32 		float fSumX = 0.0f;
33 		float fSumY = 0.0f;
34 		float fSumXY = 0.0f;
35 		float fSumX2 = 0.0f;
36 
37 		for (unsigned int uiPoint = 0; uiPoint < a_Points; uiPoint++)
38 		{
39 			fSumX += a_afX[uiPoint];
40 			fSumY += a_afY[uiPoint];
41 			fSumXY += a_afX[uiPoint] * a_afY[uiPoint];
42 			fSumX2 += a_afX[uiPoint] * a_afX[uiPoint];
43 		}
44 
45 		float fDivisor = fPoints*fSumX2 - fSumX*fSumX;
46 
47 		// if vertical line
48 		if (fDivisor == 0.0f)
49 		{
50 			*a_fSlope = 0.0f;
51 			*a_fOffset = 0.0f;
52 			return true;
53 		}
54 
55 		*a_fSlope = (fPoints*fSumXY - fSumX*fSumY) / fDivisor;
56 		*a_fOffset = (fSumY - (*a_fSlope)*fSumX) / fPoints;
57 
58 		return false;
59 	}
60 
61 	// ----------------------------------------------------------------------------------------------------
62 	//
63 
64 } // namespace Etc
65