Skip to content

Instantly share code, notes, and snippets.

@ota42y
Created February 2, 2015 22:59
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ota42y/db4ff0298d9c945cd261 to your computer and use it in GitHub Desktop.
Save ota42y/db4ff0298d9c945cd261 to your computer and use it in GitHub Desktop.
Golang least squares method
package main
import "fmt"
type Point struct {
x float64
y float64
}
func LeastSquaresMethod(points *[]Point) (a float64, b float64){
// http://ja.wikipedia.org/wiki/%E6%9C%80%E5%B0%8F%E4%BA%8C%E4%B9%97%E6%B3%95
n := float64(len(*points))
sumX := 0.0
sumY := 0.0
sumXY := 0.0
sumXX := 0.0
for _, p := range *points{
sumX += p.x
sumY += p.y
sumXY += p.x * p.y
sumXX += p.x * p.x
}
base := (n * sumXX - sumX * sumX)
a = (n * sumXY - sumX * sumY) / base
b = (sumXX * sumY - sumXY * sumX) / base
return a, b
}
func main() {
points := make([]Point, 0)
points = append(points, Point{x:0.0, y:1.0,})
points = append(points, Point{x:0.1, y:1.5,})
points = append(points, Point{x:0.2, y:2.0,})
points = append(points, Point{x:0.3, y:2.5,})
points = append(points, Point{x:0.4, y:3.0,})
points = append(points, Point{x:0.5, y:3.5,})
points = append(points, Point{x:0.6, y:4.0,})
a, b := LeastSquaresMethod(&points)
fmt.Println(a)
fmt.Println(b)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment