比如 有一组数,和另外一组数,可能长度不一样,但是曲线画出来会非常接近。
那么要比较这两组曲线是否拟合度很高,必须要将其转化为同纬度,即相同的长度,于是产生这样需求。
将一个数组 A[m]扩展成 B[n],使的该曲线线性扩展。
物理解释如下:
原来一张图画在没有拉伸的橡皮纸上,然后把这个图拉伸,用尺子重新量,可以量更多的点,然后记录下来
windows绘图可以展示,如下两图在横轴方向压缩以后必然是重合的。
可能的应用场景:
1.监控某一指标,如测试版本的负载,内存损耗~
上代码:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <math.h>
#include <string>
#include <map>
#include <iterator>
#include <vector>
#include <time.h>
#include <iostream>
using namespace std;
#define ARY_LEN_A 101
#define ARY_LEN_B 120
int expendArray(float A[], int m, float B[], int n)
{
int i = 0; // index for B
int j = 0; // index for A in the left of i
int k = 0; // index for A in the irhgt of i
float fdis = 0.0; // the distence from the start point
for(int i=1; i<n-1; i++)
{
fdis = 1.0 * (m-1) * i / (n-1);
j = (int)floor(fdis);
k = (int)ceil(fdis);
B[i] = A[j] + (A[k] - A[j]) * (fdis - j*1.0) / (k-j+0.000001);
}
B[0] = A[0];
B[n-1] = A[m-1];
}
/*
-1 : error
0 : succ
1 : fail
*/
int calcDiffCount(float A[], float B[], int n, float fthreshold)
{
int nOutFlowCount = 0;
float fAvgValue = 0;
for(int i=0; i<n; i++)
{
fAvgValue = (A[i] + B[i]) / 2.0;
if (fAvgValue * (fthreshold + 1.0) > (A[i] > B[i] ? A[i] : B[i]))
{
nOutFlowCount++;
}
}
return (nOutFlowCount > n * 0.05 ) ? 0 : 1;
}
/*
-1 : error
0 : succ
1 : fail
*/
int diffByCurveFitting(float A[], int m, float B[], int n, float threshold)
{
int nRet = 0;
if (m == n) return calcDiffCount(A, B, m, threshold);
float* pOrig = NULL;
int nMaxLen = m > n ? m : n;
float* pExpand = (float*)malloc(sizeof(float*) * nMaxLen);
if (NULL == pExpand) return -1;
if (m > n) //keep A
{
pOrig = A;
nMaxLen = m;
expendArray(B, n, pExpand, m);
}
else
{ //keep B
pOrig = B;
nMaxLen = n;
expendArray(A, m, pExpand, n);
}
nRet = calcDiffCount(pOrig, pExpand, nMaxLen, threshold);
free(pExpand);
pExpand = NULL;
return nRet;
}
int test(float fthreshold)
{
srand((int)time(0));
float fAry[ARY_LEN_A] = {};
float fBry[ARY_LEN_B] = {};
for(int i=0; i<ARY_LEN_A; i++)
{
//srand(i);
fAry[i] = 1.0 + 1000.0 * rand() / (RAND_MAX + 1.0);
}
expendArray(fAry, ARY_LEN_A, fBry, ARY_LEN_B);
for(int i=0; i<ARY_LEN_B; i++)
{
fBry[i] += (0.1 + 10.0 * rand() / (RAND_MAX + 1.0));
}
for(int i=0; i<ARY_LEN_A; i++)
{
cout << fAry[i] << "\t" << fBry[i] << endl;
}
for(int i=ARY_LEN_A; i<ARY_LEN_B; i++)
{
cout << "xx" << "\t" << fBry[i] << endl;
}
cout << "Result: ";
cout << diffByCurveFitting(fAry,ARY_LEN_A,fBry,ARY_LEN_B, fthreshold) << endl;
return 0;
}
int main(int argc, char *argv[])
{
float fthreshold = atof(argv[1]);
test(fthreshold);
return 0;
}
下图为扩展101个点到120个点后的曲线,可以看到基本是拟合的,进一步的研究还未解开