2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C#でN次関数のフィッティング

Posted at

 C#で3次関数のフィッティングが欲しかったので、簡単な関数を作ってみた。N次関数に対してフィッティングできるはず。1次関数や3次関数で試して明らかにおかしな値は出ていないはずだが、間違いなく正常に動くかどうかは確認していない。
 行列やベクトルの計算にはMath.Netを使用した

static MathNet.Numerics.LinearAlgebra.Vector<double> Fitting(ReadOnlySpan<(double x, double y)> list, int degree)
{
    var N = degree + 1;
    var mat = new double[N, N];
    var vec = new double[N];

    foreach (var (x, y) in list)
    {
        for (int i = 0; i < N; i++)
        {
            for (int j = 0; j < N; j++)
            {
                mat[i, j] += double.Pow(x, N * 2 - 2 - j - i);
            }
            vec[i] += double.Pow(x, N - 1 - i) * y;
        }
    }

    return
        MathNet.Numerics.LinearAlgebra.Double.DenseMatrix.OfArray(mat).Inverse() *
        MathNet.Numerics.LinearAlgebra.Double.DenseVector.OfArray(vec);
}

 1次関数のフィッティングの場合は

(double, double)[] a = [
    (0.0, 1.0),
    (0.2, 1.9),
    (0.4, 3.2),
    (0.6, 4.3),
    (0.8, 4.8),
    (1.0, 6.1),
    (1.2, 7.2),
];
Console.WriteLine(Fitting(a, 1));

 のようにすれば

DenseVector 2-Double
5.10714
1.00714

 のような出力が得られる。


参考にしたページ

【最小二乗法】二次関数/三次関数でフィッティング | ばたぱら

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?