Skip to content

Instantly share code, notes, and snippets.

@kuloud
Created November 1, 2016 06:34
Show Gist options
  • Select an option

  • Save kuloud/3b6d034275f199d1b6d5875cf7cee0cb to your computer and use it in GitHub Desktop.

Select an option

Save kuloud/3b6d034275f199d1b6d5875cf7cee0cb to your computer and use it in GitHub Desktop.
不等距拉格朗日插值公式
/**
不等距拉格朗日插值公式
*/
func CalcByLagrange(x []float64, y []float64, t float64) float64 {
// 初值
result := 0.0
// 特例处理
if len(x) <= 1 {
return result
}
if len(x) == 2 {
result = (y[0] * (t - x[1]) - y[1] * (t - x[0])) / (x[0] - x[1])
return result
}
// 一般情景处理
i := 0
for pos, xv := range x {
if xv < t && pos < len(x) {
i = pos + 1
}
}
// 为在可允许误差范围内简化运算,只运算插值点左右附近三个点
k := i - 4
if k < 0 {
k = 0
}
m := i + 3
if m > len(x) - 1 {
m = len(x) - 1
}
for i = k; i <= m; i++ {
s := 1.0
for j := k; j <= m; j++ {
if j != i {
// 拉格朗日插值公式
s = s * (t - x[j]) / (x[i] - x[j]);
}
}
result += s * y[i]
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment