floats: add floats LSM

This commit is contained in:
c9s 2023-05-29 17:12:34 +08:00
parent 67fe27774c
commit 89aa63dd64
No known key found for this signature in database
GPG Key ID: 7385E7E464CB0A54
3 changed files with 35 additions and 2 deletions

View File

@ -15,3 +15,9 @@ func TestHigher(t *testing.T) {
out := Higher([]float64{10.0, 11.0, 12.0, 13.0, 15.0}, 12.0)
assert.Equal(t, []float64{13.0, 15.0}, out)
}
func TestLSM(t *testing.T) {
slice := Slice{1., 2., 3., 4.}
slope := LSM(slice)
assert.Equal(t, 1.0, slope)
}

View File

@ -1,10 +1,10 @@
package floats
func (s Slice) Pivot(left, right int, f func(a, pivot float64) bool) (float64, bool) {
return CalculatePivot(s, left, right, f)
return FindPivot(s, left, right, f)
}
func CalculatePivot(values Slice, left, right int, f func(a, pivot float64) bool) (float64, bool) {
func FindPivot(values Slice, left, right int, f func(a, pivot float64) bool) (float64, bool) {
length := len(values)
if right == 0 {

View File

@ -187,3 +187,30 @@ func (s Slice) Index(i int) float64 {
func (s Slice) Length() int {
return len(s)
}
func (s Slice) LSM() float64 {
return LSM(s)
}
func LSM(values Slice) float64 {
var sumX, sumY, sumXSqr, sumXY = .0, .0, .0, .0
end := len(values) - 1
for i := end; i >= 0; i-- {
val := values[i]
per := float64(end - i + 1)
sumX += per
sumY += val
sumXSqr += per * per
sumXY += val * per
}
length := float64(len(values))
slope := (length*sumXY - sumX*sumY) / (length*sumXSqr - sumX*sumX)
average := sumY / length
tail := average - slope*sumX/length + slope
head := tail + slope*(length-1)
slope2 := (tail - head) / (length - 1)
return slope2
}