#include "my_math.h"
#include "stdint.h"
#include "stdarg.h"

void Least_Squares(uint8_t n, float x[], uint32_t y[], float* slope, float* intercept) 
{
    float sumX = 0.0, sumY = 0.0, sumXY = 0.0, sumX2 = 0.0;

    // 计算各个累加和
    for (int i = 0; i < n; i++) {
        sumX += x[i];
        sumY += y[i];
        sumXY += x[i] * y[i];
        sumX2 += x[i] * x[i];
    }

    // 计算斜率和截距
    float denominator = n * sumX2 - sumX * sumX;
    *slope = (n * sumXY - sumX * sumY) / denominator;
    *intercept = (sumY - *slope * sumX) / n;
}

void buf2int(int *tint, unsigned char *buf)
{
    int i;
    unsigned char * p1 = (unsigned char *)tint;
    unsigned char * p3 = buf;
    for (i = 0; i < 4; i++)
    {
        *p1 = *p3;
        p1++;
        p3++;
    }
}

float average(int n_values, ...)
{
    va_list var_arg;
    int count;
    float sum = 0;

    /*** 准备访问可变参数 ***/
    va_start(var_arg, n_values);

    /*** 添加取自可变参数列表的值 ***/
    for (count = 0; count < n_values; count++)
    {
        sum += va_arg(var_arg, int);
    }

    /*** 完成处理可变参数 ***/
    va_end(var_arg);

    return sum / n_values;
}

#if 0
/*位倒序*/
uint8_t Bit_Reversed(uint8_t data)
{
    uint8_t result = 0;

    for(uint8_t i = 0; i < 8; i++)
    {
        result = ((data >> i) & 0x01) | result;
        if(i < 7)
        {
           result = result << 1;
        }
    }
    return result;
}



void least_squares(uint8_t n, float x[], float y[], float* slope, float* intercept) 
{
    float sumX = 0.0, sumY = 0.0, sumXY = 0.0, sumX2 = 0.0;

    // 计算各个累加和
    for (int i = 0; i < n; i++) {
        sumX += x[i];
        sumY += y[i];
        sumXY += x[i] * y[i];
        sumX2 += x[i] * x[i];
    }

    // 计算斜率和截距
    float denominator = n * sumX2 - sumX * sumX;
    *slope = (n * sumXY - sumX * sumY) / denominator;
    *intercept = (sumY - *slope * sumX) / n;
}
#endif