« 高周波・RFニュース 2026年10月15日 アンリツがWi-Fi 8とBluetooth LE評価器発表、ローデ・シュワルツが広帯域DFアンテナ発表、TDKが環境配慮SMDバリスタ発表、5Gミリ波イミュニティ試験解説 | トップページ | 若王寺熊野大神社でお参り。阪神淡路大震災で倒壊した鳥居が復興の碑になっている。 »

2026年10月15日 (木)

Go言語の数値計算ライブラリGonumを使う(6)QR分解を使って多項式フィッティングを行う。

今回の例題はこちら。

Visual C# (C_sharp)の数学ライブラリ Math.NET Numericsを使う(4) 多項式フィッティングをして、Array.ConvertAllで一括でフィッティングデータを得る。

ただし、Gonumにはそのままずばりの多項式フィッティングはない。そこで最小二乗法をQR分解で実施して行う。

が、プログラムが長くなりそうなのでChatGPT GPT-6 Astraに書いてもらった。

コードはこちら。

package main

import (
    "fmt"
    "image/color"
    "log"
    "math"

    "gonum.org/v1/gonum/mat"
    "gonum.org/v1/plot"
    "gonum.org/v1/plot/plotter"
    "gonum.org/v1/plot/vg"
)

// PolynomialFit は
//
// y = a0 + a1*x + a2*x^2 + ... + an*x^n
//
// の係数 a0, a1, ..., an を最小二乗法で求める。
func PolynomialFit(x, y []float64, degree int) ([]float64, error) {
    if len(x) != len(y) {
        return nil, fmt.Errorf("xとyのデータ数が一致していません")
    }

    if degree < 0 {
        return nil, fmt.Errorf("degreeは0以上である必要があります")
    }

    n := len(x)

    // 未知係数は degree+1 個
    if n < degree+1 {
        return nil, fmt.Errorf(
            "%d次多項式には最低%d個のデータ点が必要です",
            degree,
            degree+1,
        )
    }

    // デザイン行列
    //
    // A =
    // [1 x0 x0^2 ... x0^degree]
    // [1 x1 x1^2 ... x1^degree]
    // [                 ...    ]
    //
    A := mat.NewDense(n, degree+1, nil)

    for i, xi := range x {
        value := 1.0

        for j := 0; j <= degree; j++ {
            A.Set(i, j, value)
            value *= xi
        }
    }

    // yベクトル
    b := mat.NewDense(n, 1, y)

    // QR分解
    var qr mat.QR
    qr.Factorize(A)

    // 最小二乗解
    var coef mat.Dense

    err := qr.SolveTo(&coef, false, b)
    if err != nil {
        return nil, fmt.Errorf("最小二乗計算に失敗しました: %w", err)
    }

    // 結果を []float64 に変換
    result := make([]float64, degree+1)

    for i := 0; i <= degree; i++ {
        result[i] = coef.At(i, 0)
    }

    return result, nil
}

// PolynomialValue は
//
// y = a0 + a1*x + a2*x^2 + ...
//
// を計算する。
//
// Horner法を使って計算する。
func PolynomialValue(x float64, coef []float64) float64 {
    if len(coef) == 0 {
        return 0
    }

    result := coef[len(coef)-1]

    for i := len(coef) - 2; i >= 0; i-- {
        result = result*x + coef[i]
    }

    return result
}

// PlotResult は元データとフィッティング曲線を描画する。
func PlotResult(
    x, y []float64,
    coef []float64,
    filename string,
) error {

    p := plot.New()

    p.Title.Text = "Polynomial Least Squares Fitting"
    p.X.Label.Text = "x"
    p.Y.Label.Text = "y"

    // ----------------------------
    // 元データ
    // ----------------------------
    points := make(plotter.XYs, len(x))

    for i := range x {
        points[i].X = x[i]
        points[i].Y = y[i]
    }

    scatter, err := plotter.NewScatter(points)
    if err != nil {
        return err
    }

    // 点を少し大きくする
    scatter.GlyphStyle.Radius = vg.Points(4)
    scatter.GlyphStyle.Color = color.RGBA{B: 255, A: 255}
    p.Add(scatter)
    p.Legend.Add("Data", scatter)

    // ----------------------------
    // xの最小値・最大値
    // ----------------------------
    xmin := math.Inf(1)
    xmax := math.Inf(-1)

    for _, xi := range x {
        if xi < xmin {
            xmin = xi
        }

        if xi > xmax {
            xmax = xi
        }
    }

    // ----------------------------
    // フィッティング曲線
    // ----------------------------
    const numPlotPoints = 500
    const offset = 1.0
    fitPoints := make(plotter.XYs, numPlotPoints)

    for i := 0; i < numPlotPoints; i++ {
        t := float64(i) / float64(numPlotPoints-1)

        xi := xmin - offset + (xmax-xmin+2.0*offset)*t
        yi := PolynomialValue(xi, coef)

        fitPoints[i].X = xi
        fitPoints[i].Y = yi
    }

    line, err := plotter.NewLine(fitPoints)
    if err != nil {
        return err
    }

    line.Width = vg.Points(2)
    line.Color = color.RGBA{R: 255, A: 255}

    p.Add(line)
    p.Legend.Add("Fitting", line)

    // グリッドを追加
    p.Add(plotter.NewGrid())

    // ----------------------------
    // PNG保存
    // ----------------------------
    err = p.Save(
        6*vg.Inch,
        4*vg.Inch,
        filename,
    )

    if err != nil {
        return err
    }

    return nil
}

func main() {

    // ==========================================
    // サンプルデータ
    // ==========================================
    x := []float64{0.0, 1.0, 2.0, 3.0, 4.0, 5.0}

    y := []float64{0.0, 0.8, 0.9, 0.1, -0.8, -1.0}

    // ==========================================
    // 多項式の次数
    // ==========================================
    degree := 3

    // ==========================================
    // フィッティング
    // ==========================================
    coef, err := PolynomialFit(x, y, degree)
    if err != nil {
        log.Fatal(err)
    }

    // ==========================================
    // 係数表示
    // ==========================================
    fmt.Printf("%d次多項式フィッティング\n\n", degree)

    for i, c := range coef {
        fmt.Printf("a%d = %12.6f\n", i, c)
    }

    // ==========================================
    // グラフ作成
    // ==========================================
    err = PlotResult(
        x,
        y,
        coef,
        "fit.png",
    )

    if err != nil {
        log.Fatal(err)
    }

}

結果はこちら。C#と同等の結果が得られた。

Fit

« 高周波・RFニュース 2026年10月15日 アンリツがWi-Fi 8とBluetooth LE評価器発表、ローデ・シュワルツが広帯域DFアンテナ発表、TDKが環境配慮SMDバリスタ発表、5Gミリ波イミュニティ試験解説 | トップページ | 若王寺熊野大神社でお参り。阪神淡路大震災で倒壊した鳥居が復興の碑になっている。 »

「パソコン・インターネット」カテゴリの記事

「学問・資格」カテゴリの記事

「日記・コラム・つぶやき」カテゴリの記事

コメント

コメントを書く

(ウェブ上には掲載しません)

« 高周波・RFニュース 2026年10月15日 アンリツがWi-Fi 8とBluetooth LE評価器発表、ローデ・シュワルツが広帯域DFアンテナ発表、TDKが環境配慮SMDバリスタ発表、5Gミリ波イミュニティ試験解説 | トップページ | 若王寺熊野大神社でお参り。阪神淡路大震災で倒壊した鳥居が復興の碑になっている。 »

最近の記事

2026年11月
日 月 火 水 木 金 土
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30          

最近のコメント

無料ブログはココログ
フォト