由于分段线性插值在每个样点小区间上相对于原函数都有很强的收敛性,数值稳定性好且容易在计算机上编程实现,在工程中得到了较为广泛的应用。在实际项目应用中编写了以下分段线性插值函数,第一个为C语言版本,第二个为VB版本。
/****************************************************************************************
*NAME: double LinearInterpolation(double *ScaleX,double *ScaleY,int ScalePointCount,double x)
*FUNCTION: 根据样点求x值的分段线性插值
*Parameter: ScaleX:数组指针,指向样点x维参数,ScaleY:数组指针,指向样点y维参数,ScalePointCount:样点数,x:待求插值的参数值
*RETURN: 返回x值的分段线性插值
*****************************************************************************************/
double LinearInterpolation(double *ScaleX,double *ScaleY,int ScalePointCount,double x)
{
double y;
int i,j;
y=0;
for(j=0;j<ScalePointCount-1;j++)
{
if(x>=ScaleX[j]&&x<=ScaleX[j+1])
{
i=j;
goto a;
}
}
i=ScalePointCount-2;
a: y=ScaleY
*(x-ScaleX[i+1])/(ScaleX-ScaleX[i+1])+ScaleY[i+1]*(x-ScaleX)/(ScaleX[i+1]-ScaleX);
return y;
}
'****************************************************************************************
'NAME: Public Function LinearInterpolation(ScaleX() As Single, ScaleY() As Single, ByVal x As Single) As Single
'FUNCTION: 根据样点求x值的分段线性插值
'Parameter: ScaleX:样点x维数组,ScaleY:样点y维数组,x:待求插值的参数值
'RETURN: 返回x值的分段线性插值
'****************************************************************************************
Public Function LinearInterpolation(ScaleX() As Single, ScaleY() As Single, ByVal x As Single) As Single
Dim i, j As Integer
For j = 0 To UBound(ScaleX) - 1
If x >= ScaleX(j) And x <= ScaleX(j + 1) Then
i = j
GoTo a
End If
Next
If x > ScaleX(UBound(ScaleX)) Then
i = UBound(ScaleX) - 1
Else
i = 0
End If
If UBound(ScaleX) = 0 Or UBound(ScaleY) = 0 Then
If x = ScaleX(0) Then
LinearInterpolation = ScaleX(0)
Else
LinearInterpolation = 0
End If
Exit Function
End If
a: LinearInterpolation = ScaleY(i) * (x - ScaleX(i + 1)) / (ScaleX(i) - ScaleX(i + 1)) + ScaleY(i + 1) * (x - ScaleX(i)) / (ScaleX(i + 1) - ScaleX(i))
End Function
青山Blog http://blog.ednchina.com/qingshan
用户377235 2012-10-13 08:23
谢谢