User Tools

Site Tools


linear_fit
linearfit.c
/************************************************************
*Linear fit
* y = ax + b
* a = S[(x - mean(X))*(y - mean(Y))]/S[(x - mean(X))*(x - mean(X))]
* b = mean(Y) - a*mean(X)
************************************************************/
void linearFit(int *values, int numberOfValues, float *results)
{
    float mean = 0;
    for (int i = 0; i < numberOfValues; i++)
    {
        mean += values[i];
    }
    mean /= (numberOfValues+1);
 
    float numerator = 0;
    float demominator = 0;
    for (int i = 0; i < numberOfValues; i++)
    {
        numerator += (values[i] - mean) * (i - numberOfValues/2);
        denominator += (values[i] - mean) * (values[i] - mean);
    }
 
    results[0] = numerator/denominator;//a - slope of the curve
 
    results[1] = numberOfValues/2 - results[0]*mean;
}
linear_fit.txt · Last modified: 2018/09/20 10:27 by supergnu