parametres input

This commit is contained in:
nuknal
2024-05-28 00:03:18 +08:00
parent 720a3fd855
commit c7bbb632f5
10 changed files with 245 additions and 90 deletions

26
fit.go
View File

@@ -1,13 +1,11 @@
package imageproc
import (
"fmt"
"gonum.org/v1/gonum/mat"
)
// PolynomialFit fits a polynomial of given degree to the data points (x, y).
func PolynomialFit(x, y []float64, degree int) []float64 {
func PolynomialFit(x, y []float64, degree int) ([]float64, error) {
n := len(x)
// Create the Vandermonde matrix
vander := mat.NewDense(n, degree+1, nil)
@@ -25,11 +23,7 @@ func PolynomialFit(x, y []float64, degree int) []float64 {
qr.Factorize(vander)
coeffs := mat.NewDense(degree+1, 1, nil)
err := qr.SolveTo(coeffs, false, yVec)
if err != nil {
panic(err)
}
return coeffs.RawMatrix().Data
return coeffs.RawMatrix().Data, err
}
// pow is a helper function to calculate power of a number.
@@ -43,19 +37,3 @@ func pow(x float64, n int) float64 {
}
return res
}
func main() {
// Input data
x := []float64{1.0, 2.0, 3.0, 4.0, 5.0}
y := []float64{1.0, 1.5, 2.5, 3.5, 5.0}
// Fit a second degree polynomial (quadratic)
degree := 2
coeffs := PolynomialFit(x, y, degree)
// Print the coefficients
fmt.Printf("Fitted polynomial coefficients: %v\n", coeffs)
if degree == 2 {
fmt.Printf("Fitted quadratic: y = %.4fx^2 + %.4fx + %.4f\n", coeffs[2], coeffs[1], coeffs[0])
}
}