VBA实现的线性插值算法源代码

分类:代码, 博客 标签:

水文应用中经常用到插值函数,如水位流量互查、水位库容互查等,而Excel作为一个常用的办公工具,如能在Excel中实现这样的函数是很实用的,这里给出一个VBA实现的线性插值算法代码,具体代码如下:

'================================
' 线性插值算法
' 
' http://cnhup.com
'================================
'Returns an interpolated value of x
'doing a lookup of xarr->yarr
Public Function Interp1(xArr As Variant, _
  yArr As Variant, _
  x As Double) As Double

If ((x < xArr(LBound(xArr))) _
  Or (x > xArr(UBound(xArr)))) Then
  MsgBox "Interp1: x is out of bound"
  Exit Function
End If

If xArr(LBound(xArr)) = x Then
  Interp1 = yArr(LBound(yArr))
  Exit Function
End If
Dim i As Single
For i = LBound(xArr) To UBound(xArr)
  If xArr(i) >= x Then
    Interp1 = yArr(i - 1) + (x - xArr(i - 1)) / (xArr(i) - xArr(i - 1)) * (yArr(i) - yArr(i - 1))
    Exit Function
  End If
Next i

End Function

如果需要拟合性更好的插值方法,可以采用一元三点插值算法,具体参考一元三点插值算法源代码



分类:代码, 博客 标签:

发表评论

You must be logged in to post a comment.