Embedded algorithm 5-linear interpolation fitting algorithm

For linearly changing physical quantities, the relationship between the measured value and the actual physical quantity can be obtained by simple conversion, but the actual majority of detected physical quantities and the converted digital quantities are not strictly linear. For example, the resistance and temperature of the thermistor, the voltage and the remaining power of the lithium battery, it is impossible to create a large correspondence table according to the resistance of 1 ohm or the voltage of 0.01v. Generally, a limited number of reference points are calibrated, and the actual value is estimated by software algorithm fitting.
Insert picture description here
Given (x0, y0) and (x1, y1), insert a node between these two values, according to the linear function g(x)=ax+b, calculate
g(x)=y0+(y1-y0) *(x-x0)/(x1-x0)
The smaller the distance between the interpolation nodes x0 and x1, the smaller the error between f(x) and g(x). Take the following data as an example.

Insert picture description here
Insert picture description here

#define N  11
//参考点
int table[N][2]={
    
    
    {
    
    0,	2},
    {
    
    10,	12},
    {
    
    20,	21},
    {
    
    30,	29},
    {
    
    40,	36},
    {
    
    50,	42},
    {
    
    60,	47},
    {
    
    70,	51},
    {
    
    80,	54},
    {
    
    90,	56},
    {
    
    100,	57}
};

int conversion(int x)
{
    
    
    int i;
    int y;

    if(x<table[0][0])
    {
    
    
        return table[0][1];
    }

    if(x>table[N-1][0])
    {
    
    
        return table[N-1][1];
    }

    for(i=0;i<N;i++)
    {
    
    
        if(x<=table[i][0])//数据排序,找到x前后的插值节点
        {
    
    
            //表示x介于table[i-1][0]~table[i][0]之间
            break;
        }
    }

    y=table[i-1][1]+(table[i][1]-table[i-1][1])*(x-table[i-1][0])/(table[i][0]-table[i-1][0]);
    return y;
}

int main(void)
{
    
    
    printf("x=25,y=%d\r\n",conversion(25));
    printf("x=75,y=%d\r\n",conversion(75));
    return 0;
  }

Output after running

x = 25, y = 25
x = 75, y = 52

Insert these two values ​​into the original curve, the effect is as follows, the newly added value basically coincides with the original curve:
Insert picture description here
linear interpolation fitting can solve the problem of estimating the corresponding relationship when the reference points are limited, the more reference points, the new fitting The smaller the value error.

Guess you like

Origin blog.csdn.net/chengjunchengjun/article/details/109241185